答:
Am I wrong to question their adherence to coding standards?

It depends on the group. Personally, I think that everything should be questioned. Some people take that questioning to be an affront; that I don't trust them.

Has anyone else experienced a similar situation and how have they dealt with it successfully?

I asked how these standards improve productivity. I measured the time I spent screwing around with the standards vs 'getting stuff done'. In the end, the powers that be decided to stick with the standards. It happens. I complained about them louder than usual when they were the cause of me not getting stuff done, but otherwise focused on getting my work done. Fighting about things continually isn't good for productivity either...

If, as you say, things are measurably worse due to the standards, then adhering to the standards should invalidate the lead's argument and leave yours. If people cannot see that (largely) objective correlation between the standard's implementation and the drop in productivity, then there's not much more you can do. Learn to deal with it, and if you can't, look for somewhere less bureaucratic.

Title: Python Coding standards vs. productivity

Body:
I work for a large humanitarian organisation, on a project building software that could help save lives in emergencies by speeding up the distribution of food. Many NGOs desperately need our software and we are weeks behind schedule.

One thing that worries me in this project is what I think is an excessive focus on coding standards. We write in python/django and use a version of PEP0008, with various modifications e.g. line lengths can go up to 160 chars and all lines should go that long if possible, no blank lines between imports, line wrapping rules that apply only to certain kinds of classes, lots of templates that we must use, even if they aren't the best way to solve a problem etc. etc.

One core dev spent a week rewriting a major part of the system to meet the then new coding standards, throwing away several suites of tests in the process, as the rewrite meant they were 'invalid'. We spent two weeks rewriting all the functionality that was lost, and fixing bugs. He is the lead dev and his word carries weight, so he has convinced the project manager that these standards are necessary. The junior devs do as they are told. I sense that the project manager has a strong feeling of cognitive dissonance about all this but nevertheless agrees with it vehemently as he feels unsure what else to do.

Today I got in serious trouble because I had forgotten to put some spaces after commas in a keyword argument. I was literally shouted at by two other devs and the project manager during a Skype call. Personally I think coding standards are important but also think that we are wasting a lot of time obsessing with them, and when I verbalized this it provoked rage. I'm seen as a troublemaker in the team, a team that is looking for scapegoats for its failings. Since the introduction of the coding standards, the team's productivity has measurably plummeted, however this only reinforces the obsession, i.e. the lead dev simply blames our non-adherence to standards for the lack of progress. He believes that we can't read each other's code if we don't adhere to the conventions.

This is starting to turn sticky. Now I am trying to modify various scripts, autopep8, pep8ify and PythonTidy to try to match the conventions. We also run pep8 against source code but there are so many implicit amendments to our standard that it's hard to track them all. The lead dev simple picks faults that the pep8 script doesn't pick up and shouts at us in the next stand-up meeting. Every week there are new additions to the coding standards that force us to rewrite existing, working, tested code. Thank heavens we still have tests, (I reverted some commits and fixed a bunch of the ones he removed).

All the while there is increasing pressure to meet the deadline.

I believe a fundamental issue is that the lead dev and another core dev refuse to trust other developers to do their job. But how to deal with that? We can't do our job because we are too busy rewriting everything.

I've never encountered this dynamic in a software engineering team. Am I wrong to question their adherence to coding standards? Has anyone else experienced a similar situation and how have they dealt with it successfully?
(I'm not looking for a discussion just actual solutions people have found)


问:
A little confused about Trac
I'm learning about the open source web based project management tool Trac and I'm a bit confused about its role in the area of reporting defects vs bug tracking.

For those unfamiliar with Trac itself, it has a Ticket system which is the tool used to report issues, and you can choose between reporting a task, an enhancement, or a defect. It's that last option that I'm confused about.

I get the impression that Trac is not meant to be a bug tracking tool, but if that's the case then what is the defect field for? I looked at the way the Trac team uses their own system, and it does look like they post some things that appear to be bugs, but for the most part it's other kinds of issues, and that actually blurries the distinction for me even further.

Can someone explain to me how the "defect" option is to be used? Is defect==bug? Should tickets be opened for bugs?

答:
I use it to track features and tasks in addition of defects.

I use the Defect option when the item I'm adding is a defect.

(I'm using Task option when it's a task, and Enhancement when it's a feature)

ContentLicense: CC BY-SA 2.5

Title: A little confused about Trac


问:
Should a stack trace be in the error message presented to the user?
I've got a bit of an argument at my workplace and I'm trying to figure out who is right, and what is the right thing to do.

Context: An intranet web application that our customers use for accounting and other ERP stuff.

I'm of the opinion that an error message presented to the user (when things crash) should include as much information as possible, including the stack trace. Of course, it has to start with a nice "An Error has occurred, please submit the below information to the developers" in large, friendly letters.

My reasoning is that a screenshot of the crashed application will often be the only easily available source of information. Sure, you can try to get a hold of the client's systems administrator(s), attempt to explain where your log files are etc., but that will probably be slow and painful (talking to the client representatives mostly is).

Also, having an immediate and full information is extremely useful in development where you don't have to go hunting through the log files to find what you need on every exception. But that could be solved with a configuration switch.

Unfortunately there has been some kind of "Security audit" (no idea how they did that without the sources), and they complained about the full exception messages citing them as a security threat. Naturally, the clients (at least one that I know of) has taken this at face value and now demands that the messages be cleaned.

I fail to see how a potential attacker could use a stack trace to figure anything out he couldn't have figured out before. Are there any examples, any documented proof of anyone ever doing that? I think that we should fight this foolish idea, but perhaps I'm the fool here, so...

Who's right?

答:
In any delivered product, the expected number of this type of error should be zero.   The utility of this information to the customer is zero.  On both counts, there's no reason to present a stack trace.  If there is some useful context, it should be presented in a customer-friendly way, not as a stack trace.

On the other hand, if the actual number of occurrences isn't zero, you desperately need this information, and shouldn't rely on the customer to send it to you. 99.99% of the time they will not.  You should install a bug reporing system that submits the information automaically, with only an "ok" from the customer.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Python Coding standards vs. productivity
I work for a large humanitarian organisation, on a project building software that could help save lives in emergencies by speeding up the distribution of food. Many NGOs desperately need our software and we are weeks behind schedule.

One thing that worries me in this project is what I think is an excessive focus on coding standards. We write in python/django and use a version of PEP0008, with various modifications e.g. line lengths can go up to 160 chars and all lines should go that long if possible, no blank lines between imports, line wrapping rules that apply only to certain kinds of classes, lots of templates that we must use, even if they aren't the best way to solve a problem etc. etc.

One core dev spent a week rewriting a major part of the system to meet the then new coding standards, throwing away several suites of tests in the process, as the rewrite meant they were 'invalid'. We spent two weeks rewriting all the functionality that was lost, and fixing bugs. He is the lead dev and his word carries weight, so he has convinced the project manager that these standards are necessary. The junior devs do as they are told. I sense that the project manager has a strong feeling of cognitive dissonance about all this but nevertheless agrees with it vehemently as he feels unsure what else to do.

Today I got in serious trouble because I had forgotten to put some spaces after commas in a keyword argument. I was literally shouted at by two other devs and the project manager during a Skype call. Personally I think coding standards are important but also think that we are wasting a lot of time obsessing with them, and when I verbalized this it provoked rage. I'm seen as a troublemaker in the team, a team that is looking for scapegoats for its failings. Since the introduction of the coding standards, the team's productivity has measurably plummeted, however this only reinforces the obsession, i.e. the lead dev simply blames our non-adherence to standards for the lack of progress. He believes that we can't read each other's code if we don't adhere to the conventions.

This is starting to turn sticky. Now I am trying to modify various scripts, autopep8, pep8ify and PythonTidy to try to match the conventions. We also run pep8 against source code but there are so many implicit amendments to our standard that it's hard to track them all. The lead dev simple picks faults that the pep8 script doesn't pick up and shouts at us in the next stand-up meeting. Every week there are new additions to the coding standards that force us to rewrite existing, working, tested code. Thank heavens we still have tests, (I reverted some commits and fixed a bunch of the ones he removed).

All the while there is increasing pressure to meet the deadline.

I believe a fundamental issue is that the lead dev and another core dev refuse to trust other developers to do their job. But how to deal with that? We can't do our job because we are too busy rewriting everything.

I've never encountered this dynamic in a software engineering team. Am I wrong to question their adherence to coding standards? Has anyone else experienced a similar situation and how have they dealt with it successfully?
(I'm not looking for a discussion just actual solutions people have found)

答:
Standards are something that shouldn't be put in place late project with a deadline looming. It's something that should have been put in place early in the project or when there's time put aside in the project schedule (preferably post initial ship) for (potentially) large offending code refactor.

If this was in fact put in late in the project, then it's a mistake made by your lead (IMHO).

However, this does not mean that if you disagree with your lead that you should just charge ahead with mutiny. This is your job. You work as a team. You have a lead. There should definitely be some level of democracy in the team, but at the end the lead is the dictator. If he says to do something, you do it.

In the end, in complying with his requests and standards, you don't provide him/her with an easy scapegoat for missing deadlines.

Also, I'm a huge advocate of coding standards (especially as the size of a team grows), but they should be implemented when it makes sense.


问:
FTP file compare
Are there any FTP programs out there that do a file comparison as well, so I can select the local and remote files and see what actually changed? I didnt find any when I googled. But it doesnt seem like a very advanced use case to me. Surely many others would have felt the need for it.. right?</p>

答: rsync, or any version control system should be better options than plain FTP. There is nothing in the FTP protocol, apart from downloading the file and checking locally, that can help you on this use case.</p>

Title: FTP file compare


问:
Abstracting away the type of a property
In Python luckily most of the times you don't have to write getters and setters to get access to class properties. That said sometimes you'll have to remember that a certain property is a list or whatnot and a property would save you there by abstracting the type and providing a setter to add something to such list for example rather than exposing the list directly.

Where do you draw the line between exposing the type directly or wrapping its access in a property? What's the general "pythonic" advice?

答:
Avoid exposing class members to the outside world. Use getters/setters instead.

The type of the actual member is unknown outside the class, and you can have several setters that set the same member. Each setter can receive different parameters and make the convertion.

I don't know Phyton but I can give you an example in pseudocode:

```<code>public class MyClass {
    private String a;

    private List<String> l = new ArrayList<String>();

    public void setA(String newValue){
        this.a = newValue;
    }

    public void setA(int newValue){
        this.a = ""+newValue;  // convert to string
    }

    public void addL(String newValue){
        l.add(newValue);
    }
}
</code>```

You then can do this with an instance of that class:

```<code>object.setA(1);
object.setA("xx");
object.addL("yy");
</code>```

Title: Abstracting away the type of a property

Body:
Avoid exposing class members to the outside world. Use getters/setters instead.

The type of the actual member is unknown outside the class, and you can have several setters that set the same member. Each setter can receive different parameters and make the convertion.

I don't know Phyton but I can give you an example in pseudocode:

public class MyClass {
    private String a;

    private List<String> l = new ArrayList<String>();

    public void setA(String newValue){
        this.a = newValue;
    }

    public void setA(int newValue){
        this.a = ""+newValue;  // convert to string
    }

    public void addL(String newValue){
        l.add(newValue);
    }
}

You then can do this with an instance of that class:

object.setA(1);
object.setA("xx");
object.addL("yy");


答:
I've been having an internal struggle with "Pythonic" code vs. "well architected" code (well, in an academic sense anyway) for a little while. The more time I spend writing Python code in a professional capacity (and dabbling in OSS), the more I realize that to be "Pythonic" is sometimes throwing away everything that you've ever learned about "correct" OOP.

Nothing in Python is truly private. As such, there is no reason to have getters and setters. Yes, you can use decorators (@property, etc), but I've found little use for them other than to bloat my code (and they're very rarely used in any code that I've looked through).

As for type checking, I rely on the user of the code to be smart enough to know what they're doing. If they use an incorrect type, somewhere down the line they'll be presented with a runtime error that should be easy enough to debug with pdb (or obvious with the error message). Again, code bloat.

Having said that, if there's something that the client code should be made aware of at runtime (data-driven content, etc), I'll use assert, which can be disabled in a non-debug environment with Python's -O flag.

The "best" Python code can be easily grokked. The less code you write (or the more you delete), the easier your code is to understand. As a shameless plug for a library I wrote, I implemented an OAuth 2.0 client that works across all server side flows and supports multiple providers out of the box in 66 LOC. Compared against one of the first revisions at ~450 LOC, that's pretty damn easy to understand ;)

After all.. We're all consenting adults here.

Title: Abstracting away the type of a property

Body:
In Python luckily most of the times you don't have to write getters and setters to get access to class properties. That said sometimes you'll have to remember that a certain property is a list or whatnot and a property would save you there by abstracting the type and providing a setter to add something to such list for example rather than exposing the list directly.

Where do you draw the line between exposing the type directly or wrapping its access in a property? What's the general "pythonic" advice?


问:
Asking for a code sample of the company at an interview
Asking a job seeker to show some code is a fairly common practice for a software company. However, would it be acceptable for the candidate to ask the interviewer to show him a small piece of code that he thinks is well written?</p>

答:
I always ask to see some code, for several reasons:

I want to know what I'm getting into. Of course no software firm is perfect, and I don't expect everyone to pump out marvels of elegance all the time (because neither do I), but if I ask for a company's very best code, and all they can show me is a sub-par spaghetti mess, I know I'm in for a miserable time, unwrapping hairballs and fighting the technical debt to get anything done. Looking at the best code a company can show establishes an upper limit of what kind of quality is possible there; even if it's unlikely that all their code looks like that, you still know it is something they strive for.

Looking at code samples tells me a lot about a company's coding culture. Do they use documentation comments? Do they lean towards an Object-Oriented style, do they have Functional Programming tendencies? Are they conservative or progressive? Do they value consistent naming, proper formatting and indentation, and neat code in general? Is the code easy to follow? How do they structure their projects? How do they approach the important things - automated testing, error handling, etc.? How defensive is their coding style?

Seeing their existing code will allow you to judge whether you can live up to their standards.

The fact that a company is willing to share code samples alone is a good sign in principle. It means that they offer me, the applicant, some trust, since their codebase is one of their most valuable assets. It also means that they are not ashamed of their code, that they are confident that showing me the code will help interest me in working with them.

If they won't show you any code samples, then that doesn't have to be a red flag, but it is wise to both ask why they won't share (quite likely, they simply can't for legal reasons), as well as explain why you want to see some. I don't think showing interest in their code is going to be seen as a negative sign, as long as you ask politely and positively.

And then there are some more side effects:

Companies, those that do agree to show you code, are unlikely to just send me a tarball of source files containing the latest version of their entire codebase, for obvious reason. If they show me any code, they will do so in the form of a little demonstration, which is great: it means I get to talk to one of my potential peers, it allows me to ask more questions about their coding culture, processes, and codebase, and ideally, it will help start a professional discussion in which I can both demonstrate skills and knowledge and learn more about the work environment. It also means that I get to look at the tools they use, which is also quite insightful - for example, if the project they show me relies heavily on a particular IDE, this means that everyone uses that, which can be good or bad. And finally, talking through a bit of code gives a good impression how well future professional communication might go.


问:
Case Class naming convention
In my recent adventures in Scala, I've found case classes to be a really nice alternative to enums when I need to include a bit of logic or several values with them. I often find myself writing structures that look like this, however:

```<code>object Foo{
  case class Foo(name: String, value: Int, other: Double)

  val BAR = Foo("bar", 1, 1.0)
  val BAZ = Foo("baz", 2, 1.5)
  val QUUX = Foo("quux", 3, 1.75)
}
</code>```

I'm primarily worried here about the naming of the object and the case class. Since they're the same thing, I end up with Foo.Foo to get to the inner class. Would it be wise to name the case class something along the lines of FooCase instead? I'm not sure if the potential ambiguity might mess with the type system if I have to do anything with subtypes or inheritance.

答:
The nested Class Foo.Foo is not the same class as Foo and there is no ambiguity. The case class Foo (the inner one) can only be accessed by it's complete name (Foo.Foo). But:

If you 'import Foo._' or 'Foo.Foo' you will run into trouble. One Solution is to use

```<code>import Foo.{Foo => InnerFoo}
</code>```

Or you don't import anything and use the complete Path (Foo and Foo.Foo). Does this answer you question?

Title: Case Class naming convention

Body:
The nested Class Foo.Foo is not the same class as Foo and there is no ambiguity. The case class Foo (the inner one) can only be accessed by it's complete name (Foo.Foo). But:

If you 'import Foo._' or 'Foo.Foo' you will run into trouble. One Solution is to use

import Foo.{Foo => InnerFoo}

Or you don't import anything and use the complete Path (Foo and Foo.Foo). Does this answer you question?


答:
In Scala there exist package objects. Thus, there is no need for searching a new name:

```<code>package foo {
  case class Foo(name: String, value: Int, other: Double)
}
package object foo {
  val Bar = Foo("bar", 1, 1.0)
  val Baz = Foo("baz", 2, 1.5)
  val Quuz = Foo("quux", 3, 1.75)
}
</code>```

Later you can import them with:

```<code>import foo._
// use all members of package `foo` and package object `foo`
</code>```

Btw, constants are usually named UpperCamelCase (as shown in my example).

Title: Case Class naming convention

Body:
In my recent adventures in Scala, I've found case classes to be a really nice alternative to enums when I need to include a bit of logic or several values with them. I often find myself writing structures that look like this, however:

```<code>object Foo{
  case class Foo(name: String, value: Int, other: Double)

  val BAR = Foo("bar", 1, 1.0)
  val BAZ = Foo("baz", 2, 1.5)
  val QUUX = Foo("quux", 3, 1.75)
}
</code>```

I'm primarily worried here about the naming of the object and the case class. Since they're the same thing, I end up with Foo.Foo to get to the inner class. Would it be wise to name the case class something along the lines of FooCase instead? I'm not sure if the potential ambiguity might mess with the type system if I have to do anything with subtypes or inheritance.

Body:
In Scala there exist package objects. Thus, there is no need for searching a new name:

package foo {
  case class Foo(name: String, value: Int, other: Double)
}
package object foo {
  val Bar = Foo("bar", 1, 1.0)
  val Baz = Foo("baz", 2, 1.5)
  val Quuz = Foo("quux", 3, 1.75)
}

Later you can import them with:

import foo._
// use all members of package `foo` and package object `foo`

Btw, constants are usually named UpperCamelCase (as shown in my example).


答:
The coding standards aren't the problem.  The problem is that management can't figure out what the problem is.  This leads to "Do something…anything!" mode.  You're looking for a rational solution, but it's an irrational problem.  The best you can do is:

Give constructive criticism of their ideas, but once the decision is made don't continually whine about it.

Do whatever you can to make the rewrites easier.

Stop stressing.  Missed deadlines are management's problem, not yours.  Do your best, but don't assume responsibility for their poor decisions.

If you know something that might help, tell them.  Your mention of standups makes it sound like you're trying to do agile, but the rest doesn't sound very agiley.  See if you can deliver limited functionality earlier instead of trying to meet one big deadline with everything.  Create user stories for the rewrites so it's clear how they are impacting the backlog.

Start looking for another job.  Seriously.  Companies in such a state aren't far away from starting to fire people.

Get some "told you so" T-shirts printed up :-)


答:
Coding standards are good. Changing coding standards is expensive (well, it's expensive if you make them less permissive; if a change to the standard leaves all existing code still compliant, it's not a problem), so should only be done when absolutely needed.

One thing to to, maybe, is to have the lead check all code prior to commit/merge/whatever to make sure it complies with the standard, since apparently the existing tool-chain seem to be unable to check it automatically.


问:
Why don't interviewers  ask the applicant to read some code?
I had a dozen interviews in my life (I'm about to graduate) and I wonder why I was only once asked to read and explain some code. Roughly, 90% jobs are mostly about maintaining existing systems. IMO ability to read someone else's code is an important skill.

Why don't interviewers check it?*

*Among my friends I am the only one that was asked to review some code.

答:
In the past I use to think that reading code should be something demonstrated in interviews, but over time I've realized that this is a waste of time for both for the interviewer and interviewee. Why? Because even bad coders can read a snip-it of code.

Being able to judge someone's ability to read code only becomes relevant when you look at something complex or code spanning many classes and files. Being able to trace code to figure out what it's doing is a desirable trait, but there just isn't enough time for someone to come up with a good example (not production code) nor is there time in an interview to ask such a question.

So, bad coders can read code, but they can't write code well. Asking to see examples of a candidates work or to ask a candidate to write code in the interview are way better indicators of their skill. If they can write out clean concise code, chances are they can read code was well.

I ask every candidate I'm interviewing a variation of the FizzBuzz problem. It's quick, simple and can normally pick out bad coders much faster than anything else I've found. A good programmer will get it very quickly and easily and it will give you a quick look in to their coding style and thought process.


问:
Is there a precedent for the license on a compiler restricting the kind of development you can use it for?
It was recently let slip that the new EULA for Delphi XE3 will prohibit Client Server development with the Professional edition without the additional purchase of a Client Server license pack. This is not to say the Professional version will lack the features, but the license will specifically prohibit the developer from using the compiler for a specific class of development, even with 3rd party or home grown solutions.

So my question is if there is a precedent of a compiler or similar creative tool prohibiting the class of work you can use it for. Specifically a commercially licensed "professional" tool like Delphi XE3. Also, would such a restriction be legally enforceable?

I know there have been educational edition or starter edition tools in the past that have restricted their use for commercial purposes, but those were not sold as "professional" tools. Also I know that a lot of computing software and equipment will have a disclaimer that it is not for use in "life support equipment" or "nuclear power" but that is more of avoiding liability than prohibiting activity.

Seems like I recall Microsoft putting a restriction in FrontPage that you couldn't use it to create a web site that reflected poorly on Microsoft, but they pulled that restriction before it could be tested legally.

Update: The EULA was dropped before the product shipped because of public resistance.

答:
It's not entirely unprecedented.

SQL Server is limited by users/server/database size, etc., effectively limiting its use as a client'server platform, and it's essentially a programming environment (albeit one with a rich data infrastructure).  Many software libraries routinely limit the way programmers can use them, in a variety of ways.

In practice, anyone can put anything they like in a license agreement.  Your remedy is to not use it if you don't like the terms, which I would imagine potential Embarcadero customers will do in droves.


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答: I'm from Quebec and a French speaking person, but all my code, comment and documentation is always done in English. But I know some companies in Quebec that enforce French in the code (comments and object/variable naming).


问:
Not specifying a return in a function, good or bad?
I have coded like this many times, and I've never encountered an issue, but the compiler always warns when it expects a return and there is none.

For instance, look at this:

```<code>-(NSString *)outputStringForInteger:(NSInteger)int
{
    if (int == 0)
    {
        return @"Number is Zero";
    }
    else
    {
        return @"Number is not Zero";
    }
    //no "failsafe" or other explicit return
}
</code>```

If the function will never get to the last line, ever, is it important to still have a failsafe option, or do you guys just deal with compiler warnings?

答:
How about this (Java - I don't know the OP's language)?</p>

```<code>String outputStringForInteger(int i)
{

   if (i == 0)
      return "Number is Zero";

   return "Number is not Zero";
}
</code>```

Body:
How about this (Java - I don't know the OP's language)?

String outputStringForInteger(int i)
{

   if (i == 0)
      return "Number is Zero";

   return "Number is not Zero";
}


问:
How much should I rely on Visual Studio's Auto Generated Code?
I'm reading about ASP.NET (VB.NET) and I want to built my professionally website. I'm wondering though; I'm still using the basics so I'm really just a novice, but how much should I rely on Visual Studio to create my elements?

Should I make my own text boxes and have my own login routine, or should I just use ASP.NET's login features?

I know eventually you have to use your own classes and such which is where the real coding comes in, but I'm not sure how relaible, flexible and secure the pre-wrote elements are?

Any help would be greatly appreciated.

答:
Im not going to pretend that I am an amazing .net developer, but I do ok. And I am always getting better. And although I agree that totally relying on visual studio auto generated code isn't the best idea, I do think it serves its purpose for learning.

It was through auto generated CRUDs in MVC that I first understood how to make them from scratch, by reading and understanding. How to edit that code and how to properly manage, edit and build upon it, I learnt how to utilise partial classes better and it often pointed me in the direction of things to research and new elements I should learn about.

Its a useful tool, and its normally fairly reliable. In my honest opinion whilst your learning use it, just make sure you learn something from it as well.


答: This is awesome if you can get it.  Sometimes it isn't possible without NDA-type agreements, but it is always good to try.  To increase your odds, let your interviewers know you want this well in advance (a couple days) so they can have something in mind to show you.</p>

Title: Asking for a code sample of the company at an interview

Body: Asking a job seeker to show some code is a fairly common practice for a software company. However, would it be acceptable for the candidate to ask the interviewer to show him a small piece of code that he thinks is well written?</p>


答:
Trac is a tool to keep track of things, assign them to people, and report on progress through state and comments.

Software development shops often have QA keep track of all the problems they've encountered (defects) and assign them to developers to fix.

Enhancments and other incidentals can also be kept track of as well, but they are not necessarily defects.

Classifying what you're doing in this manner allows the people doing metrics to sort out what's broken, what's new, and where the additional time went when work was being done that didn't fall into either category.

Title: A little confused about Trac

Body:
I'm learning about the open source web based project management tool Trac and I'm a bit confused about its role in the area of reporting defects vs bug tracking.

For those unfamiliar with Trac itself, it has a Ticket system which is the tool used to report issues, and you can choose between reporting a task, an enhancement, or a defect. It's that last option that I'm confused about.

I get the impression that Trac is not meant to be a bug tracking tool, but if that's the case then what is the defect field for? I looked at the way the Trac team uses their own system, and it does look like they post some things that appear to be bugs, but for the most part it's other kinds of issues, and that actually blurries the distinction for me even further.

Can someone explain to me how the "defect" option is to be used? Is defect==bug? Should tickets be opened for bugs?


问:
Achieving forward compatibility with C++11
I work on a large software application that must run on several platforms.  Some of these platforms support some features of C++11 (e.g. MSVS 2010) and some don't support any (e.g. GCC 4.3.x).  I expect this situation to continue for for several years (my best guess: 3-5 years).

Given that, I would like set up a compatibility interface such that (to whatever degree possible) people can write C++11 code that will still compile with older compilers with a minimum of maintenance.  Overall, the goal is to minimize #ifdef's as much as reasonably possible while still enabling basic C++11 syntax/features on the platforms that support them, and provide emulation on the platforms that don't.

Let's start with std::move().  The most obvious way to achieve compatibility would be to put something like this in a common header file:

```<code>#if !defined(HAS_STD_MOVE)
namespace std { // C++11 emulation
  template <typename T> inline T& move(T& v) { return v; }
  template <typename T> inline const T& move(const T& v) { return v; }
}
#endif // !defined(HAS_STD_MOVE)
</code>```

This allows people to write things like

```<code>std::vector<Thing> x = std::move(y);
</code>```

... with impunity.  It does what they want in C++11 and it does the best it can in C++03.  When we finally drop the last of the C++03 compilers, this code can remain as is.

However, according to the standard, it is illegal to inject new symbols into the std namespace.  That's the theory.  My question is: practically speaking is there any harm in doing this as a way of achieving forward compatibility?

答:
I've been working for a good while in keeping a level of forwards- and backwards-compatibility in my C++ programs, until I eventually had to make a library toolkit out of it, which I'm preparing for release has already been released. In general, so long as you accept that you won't get "perfect" forwards-compatibility neither in features (some things just can't be forward-emulated) not in syntax (you probably will have to use macros, alternate namespaces for some things) then you are all set.

There's a good lot of features that can be emulated in C++03 in a level that is enough for practical use - and without all the hassle that comes with eg.: Boost. Heck, even the C++ standards proposal for nullptr suggests a C++03 backport. And then there's TR1 for example for everything C++11‑but‑we've‑had‑previews‑for‑years stuff. Not only that, some C++14 features like assert variants, transparent functors and optional can be implemented in C++03!

The only two things that I know that can not absolutely be backported are constexpr and variadic templates.

With regards to the entire matter of adding stuff to namespace std, my view of it is that it doesn't matter - at all. Think of Boost, one of the most important and relevant C++ libraries, and their implementation of TR1: Boost.Tr1. If you want to improve C++, make it forwards compatible with C++11, then by definition you are turning it into something that is not C++03, so blocking yourself over a Standard that you intend to avoid or leave behind anyway is, simply put, counterproductive. Purists will complain, but by definition one needs not to care about them.

Of course, just because you won't be following the (03) Standard after all doesn't mean you can't try to, or would be going to gleefully go around breaking it. That's not the point. So long as you keep very careful control as to what is added to the std namespace, and have a control of the environments where your software is used (ie.: do testing!), there should not be any untratable harm at all. If possible, define everything in a separate namespace and only add using directives to namespace std so that you are not adding anything there beyond what "absolutely" needs to go in. Which, IINM, is more or less what Boost.TR1 does.

Update (2013): as the request of the original question and seeing some of the comments that I can not add to due to lack of rep, here is a list of C++11 and C++14 features and their degree of portability to C++03:

nullptr: fully implementable given the official Committee's backport; you'll probably have to provide some type_traits specializations as well so that it is recognized as a "native" type.

forward_list: fully implementable, though allocator support relies on what your Tr1 implmenentation can provide.

New algorithms (partition_copy, etc): fully implementable.

Container constructions from brace-sequences (eg.: vector<int> v = {1, 2, 3, 4};): fully implementable, though wordier than one would like.

static_assert: near-fully implementable when implemented as a macro (you'll only have to be careful with commas).

unique_ptr: near-fully implementable, but you'll also need support from calling code (for storing them in containers, etc); see the below though.

rvalue-references: near-fully implementable depending on how much you expect to get from them (eg.: Boost Move).

Foreach iteration: near-fully implementable, syntax will differ somewhat.

using local functions as arguments (for eg.: transform): near-fully implementable, but syntax will differ enough - for example, local functions are not defined at the call site but right before.

explicit conversion operators: implementable to practical levels (getting the conversion made explicit), see Imperfect C++'s "explicit_cast"; but integration with language features such as static_cast<> might be near-impossible.

argument forwarding: implementable to practical levels given the above on rvalue-references, but you'll need to provide N overloads to your functions taking forwardeable arguments.

move: implementable to practical levels (see the two aboves). Of course, you'd have to use modifier containers and objects to profit from this.

Scoped allocators: Not really implementable unless your Tr1 implementation can assist it.

multibyte character types: Not really implementable unless your Tr1 can support you. But for the intended purpose it's better to rely on a library specifically designed to deal with the matter, such as ICU, even if using C++11.

Variadic argument lists: implementable with some hassle, pay attention to argument forwarding.

noexcept: depends on your compiler's features.

New auto semantics and decltype: depends on your compiler's features - eg.: __typeof__.

sized integer types (int16_t, etc): depends on your compiler's features  - or you can delegate to the Portable stdint.h.

type attributes: depends on your compiler's features.

Initializer list: Not implementable to my knowledge; however if what you want is to initialize containers with sequences, see the above on "container constructions".

Template Aliasing: Not implemementable to my knowledge, but it is an unneeded feature anyway, and we've had ::type in templates forever

Variadic templates: Not implementable to my knowledge; the close is template argument defaulting, which requires N specializations, etc.

constexpr: Not implementable to my knowledge.

Uniform initialization: Not implementable to my knowledge, but guaranteed default-constructor initialization can be implemented ala Boost's value-initialized.

C++14 dynarray: fully implementable.

C++14 optional<>: near-fully implementable so long as your C++03 compiler supports alignment setups.

C++14 transparent functors: near-fully implementable, but your client code will likely have to explicitly use eg.: std::less<void> to make it work.

C++14 new assert variants (such as assure): fully implementable if you want asserts, near-fully implementable if you want to enable throws instead.

C++14 tuple extensions (get tuple element by type): fully implementable, and you can even get it to fail to compile with the exact cases described in the feature proposal.

(Disclaimer: several of these features are implemented in my C++ backports library that I have linked above, so I think I know what I'm talking about when I say "fully" or "near-fully".)


问:
Branching and CI Builds with Agile
We follow many agile processes, including automated tests, continuous integration, sprint reviews, etc... We're currently having a debate about how often we should branch release builds.

We've been doing two-week sprints and trying to deploy to production at the end of each sprint. Some of us think we should be branching every sprint. Some of us think that's overkill. If a project encompasses three Visual Studio solutions, and we branch every sprint, then that's three branches, and three CI builds to create every two weeks. If we do this for six months, we'll end up with 36 branches and 36 CI builds. There is overhead involved in that.

For those of us that think that branching every sprint is overkill, we don't have a very good alternative. On my last project, we deployed some solutions from the Main trunk. Yeah, that's not good, but it saved on some of the overhead.

What's the right way to manage branching/releasing and CI builds, using agile, when we have such short (two-week) sprint cycles?

答:
As long as you tag each release you don't need to branch. The only time you need to branch is when you need to apply a hotfix to a previous release and you cannot just upgrade your customers to latest. If you need to go back to a previous version and patch it, you branch off the tag/label.

I would read A successful Git branching model

You need to branch when you want to continue putting in new features but not give them as a patch to a previous version. What is their reasoning to create a branch every spring?

Title: Branching and CI Builds with Agile


问:
Design documents as part of Agile
At my workplace, we face a challenge in that "agile" too often has meant "vague requirements, bad acceptance criteria, good luck!"  We're trying to address that, as a general improvement effort.

So, as part of that, I am proposing that we generate design documents that, above and beyond the user story level, accurately reflect the outcome of preliminary investigations of the effect of a given feature within the system and including answers to questions that we have asked the business.

Is there an effective standard for this?

We currently face a situation where a new feature may impact multiple areas in our "big ball of mud" system, and estimates are starting to climb due to this technical debt.  Hopefully more thoughtful design processes can help.

答:
When you speak of poor requirements, the first thing that comes to mind for me is making sure you have the test criteria.  If possible create some reusable automated test cases for existing parts of the system.  Once everyone becomes comfortable with that then move to writing the test cases before the code is written.  Good test cases can do a lot to document the behaviors of a system.

As to what specific design documents to use, as other have already said, it is highly dependent on the needs of the team and what the next task they will be undertaking is.  When possible try to use tools that can generate the documents (from code) you would use, or generate the code from the document.  Maintenance of documentation can become quite expensive, so choose wisely when you persist a design document.

Personally I have had good success with class diagrams generated from code and fitnesse test cases.  The team prints out a couple of the class diagrams, do a mark-up session with the product owner and then formulate an estimate from there.  As far as fitnesse goes, I am fortunate to work with a couple of product owners who are very good at expressing what they want in spreadsheets, which are then converted to tables for fitnesse.

Title: Design documents as part of Agile


问:
What defines code readability?

Possible Duplicate:

  How would you know if you've written readable and easily maintainable code?

It is often said that readability is perhaps the most important quality-defining measure of a given piece of code for reasons concerning maintainability, ease of understanding and use.

What defines the word readable in context of program source code? What kind of definitive aspects are there to code readability?

I would be grateful with code examples of readable code, along with reasoning why it is readable.

答:
Readability, to me, means that the code is easy to follow, logically.

Standards of indentation and formatting are followed, so that the code and its structure are clearly visible.

Variables are named meaningfully, so that they communicate intent.

Comments, which are present only where needed, are concise and adhere to standard formats.

Guard clauses are used instead of nested if statements.

Facilities of the language are used skillfully, leveraging iteration and recursion rather than copy and paste coding.

Functions are short and to the point, and do one thing.

Indirection is minimized as much as possible, while still maintaining flexibility.

Unreadable:

```<code>        try:
          if item[1][2]=='1':
            qtytype='0'
            qty=str(item[1][0])
            items=item[1][0]
            amt='0.0'
            tot_amt=str(float(item[1][1])/100)
#              tot_amt=str(float(int(item[1][0])*int(item[1][1]))/100)
          else:
            qtytype='1'
            items=item[1][0]
            amt='0.0'
            tot_amt=str(float(item[1][1])/100)
            qty=0
            for entry in item[1][4]:
              qty+=entry[0]
        except TypeError:
          eType, eValue, eTraceback = sys.exc_info()
          print >> sys.stderr, time.strftime("%Y-%m-%d %H:%M:%S"), str(traceback.format_exception(eType,eValue,eTraceback))
</code>```

Readable:

```<code>item_approved = (item['approved'] == '1' and item['active'] == '1')

if item_approved:
    try:
        db_item = item.get_db_record(item['id'])
    except DoesNotExist:
        db_item = item.create_db_record(**item)

    item.approve(db_item)
    db_item.save()

    publish_event(item.events.APPROVAL)
</code>```

Title: What defines code readability?

Body:
Readability, to me, means that the code is easy to follow, logically.

Standards of indentation and formatting are followed, so that the code and its structure are clearly visible.

Variables are named meaningfully, so that they communicate intent.

Comments, which are present only where needed, are concise and adhere to standard formats.

Guard clauses are used instead of nested if statements.

Facilities of the language are used skillfully, leveraging iteration and recursion rather than copy and paste coding.

Functions are short and to the point, and do one thing.

Indirection is minimized as much as possible, while still maintaining flexibility.

Unreadable:

        try:
          if item[1][2]=='1':
            qtytype='0'
            qty=str(item[1][0])
            items=item[1][0]
            amt='0.0'
            tot_amt=str(float(item[1][1])/100)
#              tot_amt=str(float(int(item[1][0])*int(item[1][1]))/100)
          else:
            qtytype='1'
            items=item[1][0]
            amt='0.0'
            tot_amt=str(float(item[1][1])/100)
            qty=0
            for entry in item[1][4]:
              qty+=entry[0]
        except TypeError:
          eType, eValue, eTraceback = sys.exc_info()
          print >> sys.stderr, time.strftime("%Y-%m-%d %H:%M:%S"), str(traceback.format_exception(eType,eValue,eTraceback))

Readable:

item_approved = (item['approved'] == '1' and item['active'] == '1')

if item_approved:
    try:
        db_item = item.get_db_record(item['id'])
    except DoesNotExist:
        db_item = item.create_db_record(**item)

    item.approve(db_item)
    db_item.save()

    publish_event(item.events.APPROVAL)


答:
Your question was ''Am I wrong to question their adherence to coding standards?'.
http://c0x.coding-guidelines.com/Introduction.pdf (for C programming language) has some referenced studies on the value of coding guidelines. See section 9 starting on page 39.

Coding standards are implemented for a reason. One thing that seems missing from the original question is an understanding for the reason for these particular standards on the particular project (or in the particular organization). The decision to implement them on existing code was based on some logic. Without knowing the logic, it is hard to comment of 'goodness' of that decision.

I'll second what someone said that standards are implemented for 'long term productivity' - issues like maintainability of the code. Maybe some event occurred which set the project back severely because of confusion and misinterpretation.

It sounds like there is a lot of emotion on both sides - try to get to reasoned discussion.


答: It is a good idea to create a tag for each release. If you have three solutions that are released separately then that would mean three tags, I see no problem with that. Does each release have to have it's own build configuration on the CI server? It depends on how many versions you have to support. If you only need to support latest release, while working on a new one, you could get away with minimum of two build configurations: one that builds whenever changes are made to the trunk, one that builds the latest release.</p>

Title: Branching and CI Builds with Agile

Body:
We follow many agile processes, including automated tests, continuous integration, sprint reviews, etc... We're currently having a debate about how often we should branch release builds.

We've been doing two-week sprints and trying to deploy to production at the end of each sprint. Some of us think we should be branching every sprint. Some of us think that's overkill. If a project encompasses three Visual Studio solutions, and we branch every sprint, then that's three branches, and three CI builds to create every two weeks. If we do this for six months, we'll end up with 36 branches and 36 CI builds. There is overhead involved in that.

For those of us that think that branching every sprint is overkill, we don't have a very good alternative. On my last project, we deployed some solutions from the Main trunk. Yeah, that's not good, but it saved on some of the overhead.

What's the right way to manage branching/releasing and CI builds, using agile, when we have such short (two-week) sprint cycles?


答:
On our team, since going agile, we've also been trying to narrow down and understand just how much documentation is actually required. I can share with you what we've learned up to now.

Before anything else, make sure to read this article on Agile/Lean Documentation. Very good read.

Secondly, I would strongly advise you to reconsider producing design documents after preliminary work on stories. We've tried that before and it has proven to be a waste. In the middle of the last release we've decided to update the design docs ONLY AFTER the code for the story is delivered. And now I'm thinking even that is too soon.

You need to ask yourself why you want to do design docs prior to coding. For us these were the reasons:

We as a team need to understand how the story will affect the design.

Having design documents has proven useful when new (or temporary) members join the team or when returning to code that no one has worked on for over a year.  So they are useful for organizational memory to help understand how the code works.

Design documents are useful for maintenance engineers who may need to troubleshoot the code after the release.

To satisfy (1) you do not need to produce an actual design document. Your team should still have a design phase prior to coding, but that phase can be as simple as a 15 minute session in front of a whiteboard or a napkin.  You do not need to produce an actual document that will take hours (if not days) to write just to discuss the design changes.

(2) or (3) are not needed during development of the current story and more than likely they will not be needed for several subsequent iterations.

Also keep in mind that every time a team member is writing/updating design docs, that's the time that code is not being written. When you write docs before actual code, there is almost 100% chance that they will require to be updated because once you start coding design always ends up being altered.  And even if you write design docs after the code, as our team has learned, refactoring from subsequent stories still alters the design.

So what I would recommend:

Initially produce temporary designs/models enough so that your team can have an intelligent conversation prior to coding.  Do not expect to keep these and do not waste time on formalizing them.

Only produce official design documentation if someone will need it (i.e. your team has a real need for organizational memory)

Only produce design documentation on code that has been stabilized. There's no point trying to document a module that keeps being changed in every iteration.

Produce design documents which fully describe a module (or portion of the product). In the past we used to write design docs which documented the changes that have to be made. Those docs were completely worthless as soon as the release was done.

Keep the document very high-level.  If you write 20 pages covering architecture and very high-level design, that document will a) actually be read by other people and b) will help people get familiar with general layout of your code. For details people can go straight into the code.  If you write 700 pages of detailed specification, they will almost always not match reality, it is too much for anyone to read and you will end up having to maintain and update 700 pages instead of 20 whenever future changes are made.

Title: Design documents as part of Agile

Body:
At my workplace, we face a challenge in that "agile" too often has meant "vague requirements, bad acceptance criteria, good luck!"  We're trying to address that, as a general improvement effort.

So, as part of that, I am proposing that we generate design documents that, above and beyond the user story level, accurately reflect the outcome of preliminary investigations of the effect of a given feature within the system and including answers to questions that we have asked the business.

Is there an effective standard for this?

We currently face a situation where a new feature may impact multiple areas in our "big ball of mud" system, and estimates are starting to climb due to this technical debt.  Hopefully more thoughtful design processes can help.


答: Section 9 (pg 39) of http://c0x.coding-guidelines.com/Introduction.pdf gives some background for the C language coding guidelines. It is a referenced work with sociology & psychology studies. It's addressing more the question 'why code should be readable' but does address readability itself. I found it quite interesting, albeit a little 'academic' in places.</p>

Title: What defines code readability?

Body:
Possible Duplicate:

  How would you know if you've written readable and easily maintainable code?

It is often said that readability is perhaps the most important quality-defining measure of a given piece of code for reasons concerning maintainability, ease of understanding and use.

What defines the word readable in context of program source code? What kind of definitive aspects are there to code readability?

I would be grateful with code examples of readable code, along with reasoning why it is readable.


问:
How to teach Exception Handling for New Programmers?
How do you go about teaching Exception Handling to Programmers. All other things are taught easily - Data Structures, ASP.NET, WinForms, WPF, WCF - you name it, everything can be taught easily.

With Exception Handling, teaching them try-catch-finally is just the syntactic nature of Exception Handling.

What should be taught however is - What part of your code do you put in the try block? What do you do in the catch block?

Let me illustrate it with an example.

You are working on a Windows Forms Project (a small utility) and you have designed it as below with 3 different projects.

UILayer

BusinessLayer

DataLayer

If an Exception (let us say of loading an XDocument throws an exception) is raised at DataLayer (the UILayer calls BusinessLayer which in turns calls the DataLayer), do you just do the following

```<code>//In DataLayer
try {
    XDocument xd_XmlDocument = XDocument.Load("systems.xml");
}
catch(Exception ex)
{
    throw ex;
}
</code>```

which gets thrown again in the BusinessLayer and which is caught in UILayer where I write it to the log file?

Is this how you go about Exception Handling?

答:
Give an Application to the newbie which has very good Exception handling in it. Throw some exception somewhere and let them debug it with the help of Logs. By tracking the propogation of Exception they should be able to debug it. Do this exercise 3 or 4 times. Now just remove all the Exception handling from the code and let them try to track the same exception.

I believe the appreciation for the Exception Handling code will be instantly appreciated.


答:
Similar questions have been answered before. See https://stackoverflow.com/questions/550861/improving-code-readability for example.

Readable code is code that clearly communicates its intention to the reader. Code that is not readable takes longer to understand and increases the likelihood of defects.

Some things that increase readability:

Use whitespace to separate disparate areas of code. For example, indent code blocks like "if" statements. Leave blank lines between methods/functions or related lines of code within a method/function. This allows the brain to segregate the code even before the characters are read.

Use meaningful variable and method/function/class names. Follow the standard practice for the language and use terms from the problem domain if possible. The meaning and use of something should be evident from its name. Names should also be consistent (GetX(), GetY() and GetZ() rather than get_X(), LoadYFromDatabase() and getVar(Fields.Z));

Comment effectively. Avoid obvious comments ("The GetX() method returns the current value of x"). Comments should say what the code intends to do, how it relates to other parts of the code and any assumptions ("Argument "a" cannot be null. The code throws an exception if a is null").

Following established design patterns for the language, library or problem space. For example, avoid repeating code (called DRY or Don't Repeat Yourself). This wastes time as the reader tries to look for differences or find the correct piece of code to fix.

Keep it Simple (KISS principle). For example, avoid premature or unnecessary optimization. Optimization has its place but code can often be optimized without impacting readability.

Arguably the single most important aspect is consistency. It is easier to understand code if the reader knows what to expect and where to look. If the project uses conflicting variable naming and commenting styles, for example, the reader has to waste mental effort learning new styles and context switching.

The code's author may be a poor judge of readability since they may be invested in the code or be too deep in the problem to take a step back and look at it through others' eyes. Code reviews help here.

Remember that not all code is going to be readable all the time. Developers often have to write code in a hurry when they are tired using unfamiliar libraries. Poor readability should be treated like technical debt and refactored.

Title: What defines code readability?


问:
How to avoid being an API programmer only?

Possible Duplicate:

  How not to degenerate into only a programmer who stitches together APIs?

I have almost six years of experience in java. I have developed many projects which used frameworks like Struts, Spring, Hibernate, JQuery , DWR, Ajax etc.

I have used these technologies in almost all the projects I have worked on. Projects were very simple mostly with crud based apps.

My everyday tasks involves creating few screens, writing queries, testing etc.

After all these years I feel like I have turned into an API programmer who just uses these above mentioned frameworks which is not giving me any satisfaction of being a programmer.

Is this normal or is it just me who is feeling like this?

答:
First, there is nothing wrong with being an excellent API programmer. There are plenty of non-trivial challenges that can be addressed entirely within the confines of framework APIs - after all, that is the reason why these frameworks were created in the first place.

If the level of challenge at your current position does not give you enough satisfaction, try moving up the bar that you set for yourself. It is often up to you, at least to a significant degree, to decide what you make of a project assigned to you. See if you can

Complete your assignment significantly faster, or

Complete your assignment with significantly less code, or

Complete your assignment to a significantly higher standard of quality, or

Significantly decrease the amount of debugging you need to complete your assignment

Doing this consistently should eventually bring bigger and more complex assignments your way, increasing the challenge level. Usually, the new challenge would come from the business aspect of the system that you are building, not from the coding of it.


答:
If you're not constantly finding ways to push yourself outside of your comfort zone, then yes, there's a good chance that you'll feel like that. I know a lot of people who have lost (or never had) their passion for learning and are simply happy going through their daily motions. Nothing wrong with it, but it's far from me. Sounds like that's not what you enjoy either.

Do something different. Work in a different department. Find another job with a company that's not doing the same thing your company's doing, or at least has more diversity in areas that you're unfamiliar with.

Of course, if you're bound to your job for the time being because it's a good paycheck and you have real life responsibilities (i.e. you're not a fresh grad still living in your parent's basement), then take on some OS projects that put you outside of your comfort zone and force you to learn something new. Who knows? If you find something that you're passionate about, you might gain yourself enough experience to go into the field professionally (if it's something that you currently don't have enough experience doing).

Title: How to avoid being an API programmer only?

Body:
Possible Duplicate:

  How not to degenerate into only a programmer who stitches together APIs?

I have almost six years of experience in java. I have developed many projects which used frameworks like Struts, Spring, Hibernate, JQuery , DWR, Ajax etc.

I have used these technologies in almost all the projects I have worked on. Projects were very simple mostly with crud based apps.

My everyday tasks involves creating few screens, writing queries, testing etc.

After all these years I feel like I have turned into an API programmer who just uses these above mentioned frameworks which is not giving me any satisfaction of being a programmer.

Is this normal or is it just me who is feeling like this?


答:
This can be normal, particularly when you are tight on resources or people setting direction are unimaginative (not a criticism, they just might be non-technical). The big question is where do you want to go?

If you want to be a better developer, learn about the business problems you are trying to solve. Read trade magazines or blogs. Attend conferences. Do a training course. Talk to the users. The more you know about how the product is used, the more you can contribute to its direction and the more valuable an employee you will to be. You can then propose things that are a bit more adventurous than CRUD.

Expand your horizons, too. Start a side project at home to push what you know. Explore a different language or library. Find an open source project on github, write some documentation or tests for it and ask they authors if they can be added to the project.

Talk to other developers within your organization. Have a weekly lunch together where you talk about problems, debate solutions or just muse about the IT industry in general.

Alternatively, if there is someone in your organization or industry you admire, talk to them and ask them for advice. If you are respectful and appreciative, you'll be amazed how helpful others are. You could also find someone else that needs mentoring and offer to help.

Many of the tools you mention are open source. Maybe pull down their source code, learn them and submit updates. Write some training materials or short tutorials and host them on a blog.

If you want to move into management, start volunteering for situations where you can take more responsibility. Look at things outside development, too, such as being a fire warden, joining the social club or working on the 401K committee. Start learning about budgeting, basic accounting and project management.

Depending on your relationship with your manager and his/her technical expertise, it may be  worth talking about it with him or her. They might be distracted with other issues and not aware of how you feel. Indeed, if you want a promotion, do not wait for your boss suggest it to you. Driving it yourself is one of the things management looks for.


问:
What do I need to learn to decide on rename/recompile source package names because of company rebranding?
My company is currently at a rebranding process and the brand names have been used in the sources' package names but these names are only visible to developers who maintain this code so nobody from project management is really interested in changing them considering also that it would imply the recompiling of several old components.

What factors do I need to consider when deciding on a change like that?

I don't know if I should worry about legal issues or not and if so, how to address this with project management.

More background details. I have all the sources and dependencies but since the company rebranding, other development areas have adopted some of the code that needs package name-changing so I cannot take the decision only by myself so I don't make everyone else's code to crash with my core components and I cannot change other areas' code without the permission of those areas' users so yes, my concern is more political than technical. I am going try to coordinate the involved it areas to make the change anyway, since it seems to be the best approach.

Unfortunatelly in my company there's no continuous integration build server so we build our code manually on demand and to get something to production I have to justify the change (even just the package name changing) to QA with an user requirement and some other bureaucratic documentation so that's why I was hesitating the change in first place.

答:
This is usually a political/marketing question as much as technical. I have been involved in mergers where changing all references to the old name was mandated

Assuming it is just a technical question, are you missing buildable source for any of the components or are there similar significant technical risks? Will making the change break backwards compatibility when backwards compatibility is important? If the answer to either of these questions is "yes", clearly avoid the change.

Otherwise, I would recommend making the change. Changing it is only going to get harder as more development is done and, otherwise, you will need to explain it to every new developer on the project.


答:
While there's no immediate need, eventually as new code gets the new name it's going to become a pain remembering whether something uses the old or the new name.  It's a simple fix, so you may as well get it over with.  The main reason not to would be if your code was widely shared outside your company.  If you control all the source code it's only a minor inconvenience.

As far as having to recompile old components, I'm not quite sure I follow you there.  We recompile all our code a few times per day, and consider that to not be often enough.  If you're not using a continuous integration build server, it's well worth the investment.

Title: What do I need to learn to decide on rename/recompile source package names because of company rebranding?

Body:
My company is currently at a rebranding process and the brand names have been used in the sources' package names but these names are only visible to developers who maintain this code so nobody from project management is really interested in changing them considering also that it would imply the recompiling of several old components.

What factors do I need to consider when deciding on a change like that?

I don't know if I should worry about legal issues or not and if so, how to address this with project management.

More background details. I have all the sources and dependencies but since the company rebranding, other development areas have adopted some of the code that needs package name-changing so I cannot take the decision only by myself so I don't make everyone else's code to crash with my core components and I cannot change other areas' code without the permission of those areas' users so yes, my concern is more political than technical. I am going try to coordinate the involved it areas to make the change anyway, since it seems to be the best approach.

Unfortunatelly in my company there's no continuous integration build server so we build our code manually on demand and to get something to production I have to justify the change (even just the package name changing) to QA with an user requirement and some other bureaucratic documentation so that's why I was hesitating the change in first place.


问:
Should I use switch statements or long if...else chains?
Often when I hear about the switch statement, its put off as a way to replace long if...else chains. But it seems that when I use the switch statement I'm writing more code that I would be just writing if...else. You also have other issues like keeping all variables for all calls in the same scope.

Here's some code that represents the flow I normally write (thanks to diam)

```<code>String comment;   // The generated insult.
int which = (int)(Math.random() * 3);  //  Result is 0, 1, or 2.

if (which == 0) {
    comment = "You look so much better than usual.";
} else if (which == 1) {
    comment = "Your work is up to its usual standards.";
} else if (which == 2) {
    comment = "You're quite competent for so little experience.";
} else {
    comment = "Oops -- something is wrong with this code.";
}
</code>```

Then they want me to replace that with this:

```<code>String comment;   // The generated insult.
int which = (int)(Math.random() * 3);  //  Result is 0, 1, or 2.

switch (which) {
    case 0:
             comment = "You look so much better than usual.";
    break;
    case 1:
             comment = "Your work is up to its usual standards.";
    break;
    case 2:
             comment = "You're quite competent for so little experience.";
    break;
    default:
             comment = "Oops -- something is wrong with this code.";
}
</code>```

Seems like a lot more code in a much more awkward syntax. But is there really an advantage to using the switch statement?

答:
Pick something that is efficient, terse, and then document not just what you've done, but why.

Code can be revisited, and not always by its original author.

There are times when you might deliberately choose one implementation over another because you're forward-thinking about code that doesn't exist.


问:
How to match responses from a server with their corresponding requests?
There is a server that responds to requests on a socket. The client has functions to emit requests and functions to handle responses from the server.

The problem is that the request sending function and the response handling function are two unrelated functions. Given a server response X, how can I know whether it's a response to request X or some other request Y?

I would like to make a construct that would ensure that response X is definitely the answer to request X and also to make a function requestX() that returns response X and not some other response Y.

This question is mostly about the general programming approach and not about any specific language construct. Preferably, though, the answer would involve Ruby, TCP sockets, and PHP.

My code so far:

```<code>require 'socket'

class TheConnection
    def initialize(config)
        @config = config
    end
    def send(s)
        toConsole("--> #{s}")
        @conn.send "#{s}\n", 0
    end
    def connect()
        # Connect to the server
        begin
            @conn = TCPSocket.open(@config['server'], @config['port'])
        rescue Interrupt
        rescue Exception => detail
            toConsole('Exception: ' + detail.message())
            print detail.backtrace.join('\n')
            retry
        end
    end
    def getSpecificAnswer(input)
        send "GET #{input}"
    end
    def handle_server_input(s)
        case s.strip
            when /^Hello. (.*)$/i
                toConsole "[ Server says hello ]"
                send "Hello to you too! #{$1}"
            else
                toConsole(s)
        end
    end
    def main_loop()
        while true
            ready = select([@conn, $stdin], nil, nil, nil)
            next if !ready
            for s in ready[0]
                if s == $stdin then
                    return if $stdin.eof
                    s = $stdin.gets
                    send s
                elsif s == @conn then
                    return if @conn.eof
                    s = @conn.gets
                    handle_server_input(s)
                end
            end
        end
    end
    def toConsole(msg)
        t = Time.new
        puts t.strftime("[%H:%M:%S]") + ' ' + msg
    end
end
@config = Hash[
    'server'=>'test.server.com',
    'port'=>'2020'
]
$conn = TheConnection.new(@config)
$conn.connect()
$conn.getSpecificAnswer('itemsX')

begin
    $conn.main_loop()
rescue Interrupt
rescue Exception => detail
    $conn.toConsole('Exception: ' + detail.message())
    print detail.backtrace.join('\n')
    retry
end
</code>```

答:
I think I understand the question you're asking. Is it:

I have a client-server system in which the client can have multiple requests pending simultaneously. When the client receives a response, how can it tell which request corresponds to this response?

If so, there are several ways to proceed. Note that in the following discussion we distinguish between the protocol itself vs. the programming interface (API) that applications use to drive the protocol.

0. Use an established protocol.

There are many subtleties involved in developing protocols. Existing protocols such as HTTP may have solved these issues satisfactorily for your application already, and there are many APIs for it already available. I'm with BicycleDude, use an existing protocol if possible. However, if you can't use an existing protocol for some reason, read on.

1. Make the protocol and API fully synchronous.

This is the simplest approach. When the client issues a request, it blocks reading from the socket until it receives the response -- the entire response. Then it returns the response to the caller. This is changing the protocol so that there is at most one request pending at any given time. The response received unambiguously corresponds to the request just sent. The API is simple, because the caller issues the request and server's response can be the return value of the function called to issue the request.

The problem is that it's slow. Each request suffers round-trip latency to the server. The client can't do anything else while it's waiting. (Unless the client is multi-threaded.)

You should seriously consider this approach (if you've decided not to reuse an existing protocol). This is similar in style to RPC (Remote Procedure Calls). The latency issues can be irritating, but the implementation and programming model are simple. If you decide to step away from being fully synchronous, things get complicated very fast.

2. Allow pipelining in the protocol, and make the API asynchronous.

"Pipelining" means that multiple requests can be pending, but that the server is required to process and to respond to each request in order. The client keeps track of which requests are pending and, since the responses come in order, it knows which request corresponds to which response.

There is great diagram on the Wikipedia article for HTTP pipelining. See, you really should consider using HTTP. :-)

The programming model gets more complicated now. When the client issues a request Request1, the call returns immediately and doesn't wait for the corresponding response Response1. Now the application can continue doing other work and eventually issue Request2 in the same way. How does the application get its responses? The usual way is for the API to return some object that represents the pending request. When the application wants to get the response for that request, it makes a call on that object. The pseudo-code would look something like this:

```<code>request1 = send_request(...)
...
response1 = request1.get_response()
</code>```

Now, note that the application can ask for responses in a different order from which the requests were issued:

```<code>request1 = send_request(...)
request2 = send_request(...)
...
response2 = request2.get_response()
</code>```

How does this work? The client will receive response1 over the network first, but that's not what the application is asking for -- it's asking for response2. So the client (presumably somewhere in a library) will have to buffer up response1 and then read, possibly waiting for, response2 to come in. Now we have a situation where the library needs to buffer up a potentially arbitrary amount of responses until the application asks for those specific responses. If the application forgets to do so, well, that's a memory leak. The library may also need to cancel a pending request; this doesn't really cancel it, but basically just tells the library to discard that particular response.

3. Make the protocol asynchronous.

This variation allows the server to respond to requests out-of-order. This could happen if the server processes its requests using a thread pool. Whenever a server thread completes its work, it sends its response, regardless of the order in which the requests were received.

So, the client might issue request1 and then request2, but the server might send response2 first. This variation has the same client-side buffering and request-response tracking issues, but now the protocol itself has to keep track of which response corresponds to which request. The usual way to do this is with sequence numbers or IDs. The client sends a sequence number along with every request. This number must be unique, at least unique enough so that no two pending requests ever have the same ID. Then, the server has to put this ID number in every response.

Still other variations are possible, for example, allowing the server to send zero or more than one response to each request, or allowing the server to send messages spontaneously (that is, not in response to any particular request).

Good luck!

Body:
I think I understand the question you're asking. Is it:

I have a client-server system in which the client can have multiple requests pending simultaneously. When the client receives a response, how can it tell which request corresponds to this response?

If so, there are several ways to proceed. Note that in the following discussion we distinguish between the protocol itself vs. the programming interface (API) that applications use to drive the protocol.

0. Use an established protocol.

There are many subtleties involved in developing protocols. Existing protocols such as HTTP may have solved these issues satisfactorily for your application already, and there are many APIs for it already available. I'm with BicycleDude, use an existing protocol if possible. However, if you can't use an existing protocol for some reason, read on.

1. Make the protocol and API fully synchronous.

This is the simplest approach. When the client issues a request, it blocks reading from the socket until it receives the response -- the entire response. Then it returns the response to the caller. This is changing the protocol so that there is at most one request pending at any given time. The response received unambiguously corresponds to the request just sent. The API is simple, because the caller issues the request and server's response can be the return value of the function called to issue the request.

The problem is that it's slow. Each request suffers round-trip latency to the server. The client can't do anything else while it's waiting. (Unless the client is multi-threaded.)

You should seriously consider this approach (if you've decided not to reuse an existing protocol). This is similar in style to RPC (Remote Procedure Calls). The latency issues can be irritating, but the implementation and programming model are simple. If you decide to step away from being fully synchronous, things get complicated very fast.

2. Allow pipelining in the protocol, and make the API asynchronous.

"Pipelining" means that multiple requests can be pending, but that the server is required to process and to respond to each request in order. The client keeps track of which requests are pending and, since the responses come in order, it knows which request corresponds to which response.

There is great diagram on the Wikipedia article for HTTP pipelining. See, you really should consider using HTTP. :-)

The programming model gets more complicated now. When the client issues a request Request1, the call returns immediately and doesn't wait for the corresponding response Response1. Now the application can continue doing other work and eventually issue Request2 in the same way. How does the application get its responses? The usual way is for the API to return some object that represents the pending request. When the application wants to get the response for that request, it makes a call on that object. The pseudo-code would look something like this:

request1 = send_request(...)
...
response1 = request1.get_response()

Now, note that the application can ask for responses in a different order from which the requests were issued:

request1 = send_request(...)
request2 = send_request(...)
...
response2 = request2.get_response()

How does this work? The client will receive response1 over the network first, but that's not what the application is asking for -- it's asking for response2. So the client (presumably somewhere in a library) will have to buffer up response1 and then read, possibly waiting for, response2 to come in. Now we have a situation where the library needs to buffer up a potentially arbitrary amount of responses until the application asks for those specific responses. If the application forgets to do so, well, that's a memory leak. The library may also need to cancel a pending request; this doesn't really cancel it, but basically just tells the library to discard that particular response.

3. Make the protocol asynchronous.

This variation allows the server to respond to requests out-of-order. This could happen if the server processes its requests using a thread pool. Whenever a server thread completes its work, it sends its response, regardless of the order in which the requests were received.

So, the client might issue request1 and then request2, but the server might send response2 first. This variation has the same client-side buffering and request-response tracking issues, but now the protocol itself has to keep track of which response corresponds to which request. The usual way to do this is with sequence numbers or IDs. The client sends a sequence number along with every request. This number must be unique, at least unique enough so that no two pending requests ever have the same ID. Then, the server has to put this ID number in every response.

Still other variations are possible, for example, allowing the server to send zero or more than one response to each request, or allowing the server to send messages spontaneously (that is, not in response to any particular request).

Good luck!


问:
What is faster and preferable way for variable assignment in ruby?
I am a RoR developer and want to clarify some doubt about ruby variable assignment.

In ruby we have two ways for variable assignment.

```<code>str, arr, num = "Hi", [1, 2], 3
</code>```

and

```<code>str = "Hi"
arr = [1, 2]
num = 3
</code>```

I know that the first way will go slower than second way but, I want to know that as per ruby language, which way is preferable and performance reliable?

答:
"Writing Efficient Ruby Code" by Dr. Stefan Kaes has this to say about parallel assignment (your first example):

Like any other Ruby expression, a value needs to be returned from a
  parallel assignment. The value returned by a parallel assignment is
  the value of the expression on the right-hand side of the assignment.
  This means Ruby needs to create an array if the right-hand side is a
  list of expressions:

```<code>$ irb
>> a,b = 1,2
=> [1, 2]
</code>```

Of course, if the assignment isn’t the last statement of a method, the
  created array becomes garbage immediately. It’s therefore advisable to
  avoid the use of parallel assignment in performance-critical code
  sections.

Dr. Kaes goes on to speculate that Ruby 1.9 may change the semantics of parallel assignments to always return true for performance reasons.

To my eye, parallel assignment aids neither clarity nor maintainability, so, performance reasons aside, I would avoid it as a matter of course.

Body:
"Writing Efficient Ruby Code" by Dr. Stefan Kaes has this to say about parallel assignment (your first example):

Like any other Ruby expression, a value needs to be returned from a
  parallel assignment. The value returned by a parallel assignment is
  the value of the expression on the right-hand side of the assignment.
  This means Ruby needs to create an array if the right-hand side is a
  list of expressions:

$ irb
>> a,b = 1,2
=> [1, 2]

Of course, if the assignment isn’t the last statement of a method, the
  created array becomes garbage immediately. It’s therefore advisable to
  avoid the use of parallel assignment in performance-critical code
  sections.

Dr. Kaes goes on to speculate that Ruby 1.9 may change the semantics of parallel assignments to always return true for performance reasons.

To my eye, parallel assignment aids neither clarity nor maintainability, so, performance reasons aside, I would avoid it as a matter of course.


答:
How many source files are you talking about?  If lots then it starts to become a problem.

But then again, I presume the Grown Ups factored the costs involved when considering the rebranding? Or did they just consider the reprint of letter heads and business cards?

My view (which seems to match the previous commentators) would be to JFDI...  perhaps to keep QA happy, raise a standalone change request (or whatever the company parlance is) to do it - in theory this should be a "no executable impact" change - ie the new output should be the same as the old one.

Perhaps also, you should increment the major version, to start as a clean slate?


答:
Second option is preferable in most of the cases. However first case is more readable in some situations.

If you have common kind of variables or an array you can use first case. Example:

arr1, arr2, arr3 ... arr20 = 1, 2, 3 ... 20

In this case using 1 line of code is more preferable then using 20 different statements. Code is more readable.

If you are going to use parallel assignments you need to take care of assignment flow

Title: What is faster and preferable way for variable assignment in ruby?

Body:
I am a RoR developer and want to clarify some doubt about ruby variable assignment.

In ruby we have two ways for variable assignment.

```<code>str, arr, num = "Hi", [1, 2], 3
</code>```

and

```<code>str = "Hi"
arr = [1, 2]
num = 3
</code>```

I know that the first way will go slower than second way but, I want to know that as per ruby language, which way is preferable and performance reliable?


问:
Python Coding standards vs. productivity
I work for a large humanitarian organisation, on a project building software that could help save lives in emergencies by speeding up the distribution of food. Many NGOs desperately need our software and we are weeks behind schedule.

One thing that worries me in this project is what I think is an excessive focus on coding standards. We write in python/django and use a version of PEP0008, with various modifications e.g. line lengths can go up to 160 chars and all lines should go that long if possible, no blank lines between imports, line wrapping rules that apply only to certain kinds of classes, lots of templates that we must use, even if they aren't the best way to solve a problem etc. etc.

One core dev spent a week rewriting a major part of the system to meet the then new coding standards, throwing away several suites of tests in the process, as the rewrite meant they were 'invalid'. We spent two weeks rewriting all the functionality that was lost, and fixing bugs. He is the lead dev and his word carries weight, so he has convinced the project manager that these standards are necessary. The junior devs do as they are told. I sense that the project manager has a strong feeling of cognitive dissonance about all this but nevertheless agrees with it vehemently as he feels unsure what else to do.

Today I got in serious trouble because I had forgotten to put some spaces after commas in a keyword argument. I was literally shouted at by two other devs and the project manager during a Skype call. Personally I think coding standards are important but also think that we are wasting a lot of time obsessing with them, and when I verbalized this it provoked rage. I'm seen as a troublemaker in the team, a team that is looking for scapegoats for its failings. Since the introduction of the coding standards, the team's productivity has measurably plummeted, however this only reinforces the obsession, i.e. the lead dev simply blames our non-adherence to standards for the lack of progress. He believes that we can't read each other's code if we don't adhere to the conventions.

This is starting to turn sticky. Now I am trying to modify various scripts, autopep8, pep8ify and PythonTidy to try to match the conventions. We also run pep8 against source code but there are so many implicit amendments to our standard that it's hard to track them all. The lead dev simple picks faults that the pep8 script doesn't pick up and shouts at us in the next stand-up meeting. Every week there are new additions to the coding standards that force us to rewrite existing, working, tested code. Thank heavens we still have tests, (I reverted some commits and fixed a bunch of the ones he removed).

All the while there is increasing pressure to meet the deadline.

I believe a fundamental issue is that the lead dev and another core dev refuse to trust other developers to do their job. But how to deal with that? We can't do our job because we are too busy rewriting everything.

I've never encountered this dynamic in a software engineering team. Am I wrong to question their adherence to coding standards? Has anyone else experienced a similar situation and how have they dealt with it successfully?
(I'm not looking for a discussion just actual solutions people have found)

答:
As you've probably seen by the other answers and comments, your project has big problems, so what I'm going to suggest doesn't have a big chance of success, but it's something you can try without too big risk with regards to your own skin.

Ask for a meeting between four eyes with your lead developer. Say that you are interested in thoroughly understanding the benefits of being so strict with the coding standard and why the codebase was in such a bad shape before introducing them. It's very important that you keep a very open and "I'm trying to learn" attitude during this discussion. Your lead developer is probably already more stressed than you or anyone else on your team is, and will probably be very defensive as soon as he smells some critisicm.

Try to nudge the discussion into the direction of trying to figure out ways to meet your common goal; delivering working and maintainable software promptly.

For example, some low hanging fruit is to not add anything more to the coding guidelines. Everytime that happens, code that previously adhered to the guidelines no longer does, and this results in that you need to rewrite chunks of code. Hopefully your lead dev can see that even if the added rule adds value (from his point of view), it might not do as much good as to motivate the rewrite at this phase of the already late project.

If this works, you can try to have him remove the more arbitrary rules that can't be autoformatted with some tool.


答:
software that could help save lives in emergencies by speeding up the distribution of food

I believe in good coding standards, but I believe also that saving lives is much more important.

Your biggest priority must be saving people's lives. Imagine if this software is distributing food to your family, or your team. Anything else can come next.

The good news: you have tests. Tests will help you comply with your coding standards without breaking functionality, but this should happen after shipping, not before.

Body:
I work for a large humanitarian organisation, on a project building software that could help save lives in emergencies by speeding up the distribution of food. Many NGOs desperately need our software and we are weeks behind schedule.

One thing that worries me in this project is what I think is an excessive focus on coding standards. We write in python/django and use a version of PEP0008, with various modifications e.g. line lengths can go up to 160 chars and all lines should go that long if possible, no blank lines between imports, line wrapping rules that apply only to certain kinds of classes, lots of templates that we must use, even if they aren't the best way to solve a problem etc. etc.

One core dev spent a week rewriting a major part of the system to meet the then new coding standards, throwing away several suites of tests in the process, as the rewrite meant they were 'invalid'. We spent two weeks rewriting all the functionality that was lost, and fixing bugs. He is the lead dev and his word carries weight, so he has convinced the project manager that these standards are necessary. The junior devs do as they are told. I sense that the project manager has a strong feeling of cognitive dissonance about all this but nevertheless agrees with it vehemently as he feels unsure what else to do.

Today I got in serious trouble because I had forgotten to put some spaces after commas in a keyword argument. I was literally shouted at by two other devs and the project manager during a Skype call. Personally I think coding standards are important but also think that we are wasting a lot of time obsessing with them, and when I verbalized this it provoked rage. I'm seen as a troublemaker in the team, a team that is looking for scapegoats for its failings. Since the introduction of the coding standards, the team's productivity has measurably plummeted, however this only reinforces the obsession, i.e. the lead dev simply blames our non-adherence to standards for the lack of progress. He believes that we can't read each other's code if we don't adhere to the conventions.

This is starting to turn sticky. Now I am trying to modify various scripts, autopep8, pep8ify and PythonTidy to try to match the conventions. We also run pep8 against source code but there are so many implicit amendments to our standard that it's hard to track them all. The lead dev simple picks faults that the pep8 script doesn't pick up and shouts at us in the next stand-up meeting. Every week there are new additions to the coding standards that force us to rewrite existing, working, tested code. Thank heavens we still have tests, (I reverted some commits and fixed a bunch of the ones he removed).

All the while there is increasing pressure to meet the deadline.

I believe a fundamental issue is that the lead dev and another core dev refuse to trust other developers to do their job. But how to deal with that? We can't do our job because we are too busy rewriting everything.

I've never encountered this dynamic in a software engineering team. Am I wrong to question their adherence to coding standards? Has anyone else experienced a similar situation and how have they dealt with it successfully?
(I'm not looking for a discussion just actual solutions people have found)