问:
Is it possible for a one-man start-up to follow agile methods like Scrum?
For a small start-up with only one or two programmers, is it possible to implement agile methods like Scrum? If NO, what is the minimum team size required?

I guess Scrum needs few programmers to be onsite as well?

 Edited **
I think the Agile methods are meant for team collaboration and improve workflow so a single man may not benefit much.

答: Of course you can follow agile methods. However, I don't think that Scrum would be adequate in your case. I agree with Agile Scout - try Kanban. I recommend you reading articles, which are published at Kanban Library   </p>


问:
Asking back technical questions during the interview (as the interviewee)
I would like to know if people have already asked back some technical questions to your interviewer. Saying something like "Well, you asked me a bunch of technical questions, and now, do you mind if I ask you some? If I am going to join your company, we will work closely together and I want to make sure my I respect the skills of my coworkers like they respect mine...".

Doesn't it sound arrogant? I am curious to have your opinion or experience (as the interviewee or the interviewer, of course).

P.S: throwaway account as I dont want that people who know me know I am preparing interviews.

答:
When I give interviews, if you don't ask questions I take it as a sign you aren't interested. Asking a question isn't inherantly arrogant. how you ask, however, can be construed as arrogance. The way you phrased it in your question comes across as arrogant "... like they respect mine.".

Be open, honest, naturally curious, factual. Don't ask loaded questions, and don't ask them to prove their technical skills to you.

ContentLicense: CC BY-SA 3.0


答:
Do you really need to ask questions in such a straightforward fashion?

I wouldn't say anything like "I want to be sure I respect the skills of my coworkers." because, honestly, if I were an interviewer, I wouldn't like it.

It's always about compatibility. You can think something along the lines of "I don't respect him because he didn't give me the right answer", but I don't think you should put it that way.  Even if you think there's a right answer, even if there really is a right answer, it's always nicer to think of things in terms of compatible or not compatible rather than right or wrong. Showing the latter attitude can be off-putting.

That's why I agree with others who say that you should try to find out the information you need less directly. Ask about the way they do things, to see if their way of doing things and your way of doing things are compatible (even if what you really want is to see is their level of competence).

Also, you can search for the information online, maybe talk to some people who work in that company.

Having said that, you could ask your question if you can afford to do so (because you're a programming superstar or whatever) and if you're looking for an environment in which you don't have to be tactful and in which people like questions like that. But, if all you really want to know is how much technical skills they have, there's no reason to ask your questions in such a direct (and perhaps slightly impolite) manner.

Title: Asking back technical questions during the interview (as the interviewee)

Body:
I would like to know if people have already asked back some technical questions to your interviewer. Saying something like "Well, you asked me a bunch of technical questions, and now, do you mind if I ask you some? If I am going to join your company, we will work closely together and I want to make sure my I respect the skills of my coworkers like they respect mine...".

Doesn't it sound arrogant? I am curious to have your opinion or experience (as the interviewee or the interviewer, of course).

P.S: throwaway account as I dont want that people who know me know I am preparing interviews.


问:
Why rpm and deb package formats are not unified into one standard system?
I had this question asked on stackoverflow, but it was closed "as not a real question".

So i decided to remove all rumbling and post that question here, assuming that this stackexchange is for "conceptual questions about software development"

The main question is in the title: Why rpm and deb package formats are not unified into one standard system?

I think that this is very important step, which we need to do, because such format fragmentation is bad, and not only for independant software developers, but for other tools and languages, who reinventing own packaging, like vim, python, ruby, nodejs, php, eclipse and many many others

答:
Because that would create anther standard, and you would still have to support both rpm and deb.

The natural way is for one to show that it is so superior that people stop using the other.


问:
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?

答:
Not sure what language you're in so I'll use Java for my example.

```<code>String outputStringForInteger(int i) {
   String returnString = "Number is not Zero";

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

   return returnString;
}
</code>```

This will provide a "default" return value, as well as being more readable(IMO).

ContentLicense: CC BY-SA 2.5

Body:
Not sure what language you're in so I'll use Java for my example.

String outputStringForInteger(int i) {
   String returnString = "Number is not Zero";

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

   return returnString;
}

This will provide a "default" return value, as well as being more readable(IMO).


问:
Recurring Problem - need instruction to run only once inside code which executes multiple times
I come across this problem usually (especially when dealing with certain frameworks) where I would like once piece of code to execute once and only once however the provided method e.g (something like an onComplete function) that I wish to place this instruction in will in reality execute multiple times.

I am just wondering does anybody know of the best way that would get around this problem, one programmer friend of mine told me to use a flag (boolean) to check whether or not this code has already run but I feel like this is not a suitable solution and I would not like to introduce global variables for the sake of checking a condition once and only once.

Has anybody ever come across a problem like this before, I am wondering is there any good practice out there to keep in mind when dealing with code like this.

答:
The way it's done in Grand Central Dispatch is to use a semaphore type called a "once token". Your code would look something like this:

```<code>void do_something_once(once_token *token, void (*work)()) {
  if(atomic_read(token) == 0) {
    atomic_increment(token);
    work();
  }
}

void initialize() {/* the work */}

static once_token do_once = 0;
do_something_once(&do_once, initialize);
</code>```

Where the details of atomically reading and incrementing the token depend on your platform.

Body:
The way it's done in Grand Central Dispatch is to use a semaphore type called a "once token". Your code would look something like this:

void do_something_once(once_token *token, void (*work)()) {
  if(atomic_read(token) == 0) {
    atomic_increment(token);
    work();
  }
}

void initialize() {/* the work */}

static once_token do_once = 0;
do_something_once(&do_once, initialize);

Where the details of atomically reading and incrementing the token depend on your platform.


答:
This is because DEB and RPM are essentially different ways of doing things and could be seen as a sort of disagreement resulting in two separate systems.

Here is an interesting discussion on the matter:
https://unix.stackexchange.com/questions/634/what-are-the-pros-cons-of-deb-vs-rpm

There is an attempt to standardize on package formats in the Linux Standards Base project, however it seems that Debian was excluded from giving input and a subset of RPM was chosen as the package format. From wikipedia:

Choice of RPM package format

The LSB specifies that software packages should either be delivered as
  an LSB-compliant installer[11], or (preferably) be delivered in a
  restricted form of the RPM Package Manager format.[12]

This choice of package format precludes the use of the many other,
  existing package formats not compatible with RPM. To address this, the
  standard does not dictate what package format the system must use for
  its own packages, merely that RPM must be supported to allow packages
  from third-party distributors to be installed on a conforming system.

Limitations on Debian

Debian has included optional support for the LSB early on, at version
  1.1 in "woody" and 2.0 in "sarge", and later 3.1 in "etch" and 3.2 in "lenny". To use foreign LSB-compliant RPM packages, the end-user needs
  to use Debian's Alien program to transform them into the native
  package format and then install them.

The LSB-specified RPM format has a restricted subset of RPM
  features—to block usage of RPM features that would be untranslatable
  to .deb with Alien or other package conversion programs, and vice
  versa, as each format has capabilities the other lacks. In practice,
  not all Linux binary packages are necessarily LSB-compliant, so while
  most can be converted between .rpm and .deb, this operation is
  restricted to a subset of packages.

By using Alien, Debian is LSB-compatible for all intents and purposes,
  but according to the description of their lsb package,[13] the
  presence of the package "does not imply that we believe that Debian
  fully complies with the Linux Standard Base, and should not be
  construed as a statement that Debian is LSB-compliant."[13]

In general, Debian does strive to comply with the LSB, but there may
  be other limitations.[14]

From what I have read the feature sets are so different that it would be very difficult to merge the two. There does seem to at least be a desire to standardize, but if I had to take a bet I would say that Debian's packagae management system will probably eventually take over, simply because of the sheer market share of Ubuntu and some packagers either only doing Debian packages or doing Debian packages first.

Body:
I had this question asked on stackoverflow, but it was closed "as not a real question".

So i decided to remove all rumbling and post that question here, assuming that this stackexchange is for "conceptual questions about software development"

The main question is in the title: Why rpm and deb package formats are not unified into one standard system?

I think that this is very important step, which we need to do, because such format fragmentation is bad, and not only for independant software developers, but for other tools and languages, who reinventing own packaging, like vim, python, ruby, nodejs, php, eclipse and many many others


问:
Should session variables be avoided?
I used to heavily rely on session variables in the past, but have recently found many of them to be unnecessary, using things like query string parameters instead.

A colleague of mine refuses to use session variables. Is this a realistic goal and should session variables be avoided for any practical reasons? Can session variables be avoided completely (except for session cookies to allow logins) and would this result in better designs?

Some of the reasons my colleague has for not using them:

Untyped nature of session variables

Session time-outs causing loss of state

Global scope nature of session variables

Load balancing servers losing sessions (.Net specific?)

Application pools/servers restarting

They are unnecessary

答:
The HTTP protocol is stateless.  Sessions are a way to preserve client state across HTTP requests.  You may choose to do that with a platform's built-in session handling or do it yourself with query string parameters.  Either way some concept of a session is necessary for many tasks.

Your colleague probably dislikes a specific implementation, or hasn't been using sessions for their intended purposes.  If you need to retain information about a specific client connection across HTTP requests, you need some form of session persistence.

The following issues are implementation specific:

Untyped nature of session variables

Global scope nature of session variables

Load balancing servers losing sessions

Application pools/servers restarting

For example, I most often work in PHP and store my session information in a relational database.  So my session variables are typed.  Load balancing and server restarts don't cause any session issues.

This one is more interesting:

Session time-outs causing loss of state

Sessions are most often preserved via cookies.  These can be deleted by the client at any time.  But they can also be preserved via a query string parameter and therefore never time out on the client.  The server timeout is up to you.  So even this issue is implementation specific.

Let's not throw out the entire concept of sessions just because we don't like a particular implementation.  Any good web application framework will facilitate using sessions properly to preserve user logins or retain anything else specific to the user's current visit.  A user's database record can (and should) be used to store things specific to them when logged in.  Anonymous visitors, however, may have temporary information also worth preserving in their session, such as a short list of recent pages visited or the preference to hide a notice they've already seen.  Generally only smaller temporary information is appropriate for session storage.

Title: Should session variables be avoided?


问:
What is abstraction?
Is there a generally agreed upon definition for what a programming abstraction is, as used by programmers? [Note, programming abstraction is not to be confused with dictionary definitions for the word "abstraction."] Is there an unambiguous, or even mathematical definition? What are some clear examples of abstractions?

答:
An abstraction is representing something (e.g. a concept, a data structure, a function) in terms of something else.  For example we use words to communicate.  A word is an abstract entity that can be represented in terms of sounds (speech) or in terms of graphical symbols (writing).  The key idea of an abstraction is that the entity in question is distinct from the underlying representation, just as a word is not the sounds that are used to utter it or the letters that are used to write it.

Thus, at least in theory, the underlying representation of an abstraction can be replaced by a different representation.  In practice, however, the abstraction is rarely entirely distinct from the underlying representation, and sometimes the representation "leaks" through.  For example, speech carries emotional undertones which are very difficult to convey in writing.  Because of this an audio recording and a transcript of the same words may have very different effect on the audience.  In other words the abstraction of words often leaks.

Abstractions typically come in layers.  Words are abstractions that can be represented by letters, which in turn are themselves abstractions of sounds, which are in their turn abstractions of the pattern of motion of the particles of air that are created by one's vocal chords and that are detected by one's ear drums.

In computer science bits are typically the lowest level of representation.  Bytes, memory locations, assembly instructions, and CPU registers are the next level of abstraction.  Then we have primitive data types and instructions of a higher level language, that are implemented in terms of bytes, memory locations, and assembly instructions.  Then functions and classes (assuming an OO language) that are implemented in terms of primitive data types and built in language instructions.  Then more complex functions and classes are implemented in terms of the simpler ones.  Some of these functions and classes implement data structures, such as lists, stacks, queues, etc.  Those in turn are used to represent more specific entities such as a queue of processes, or a list of employees, or a hash table of book titles. In this scheme of things each level is an abstraction with respect to its predecessor.

Title: What is abstraction?


问:
Running time insensitive to input?
I read the following in Algorithms 4th Edition by Robert Sedgewick and Kevin Wayne:

Our first qualitative observation about most programs is that there is a problem size that characterizes the difficulty of the computational task. Normaly, the problem size is either the size of the input or the value of a command-line argument. Intuitively, the running time should increase with problem size, but the question is by how much it increases...

and

Another qualitative observation for many programs is that the running time is relatively insensitive to the input itself; it depends primarily on the problem size. If this relationship does not hold, we need to take steps to better understand and perhaps better control the runnig time's sensitivity to the input. But it does ofter hold, so we now focus on the goal of better quantifying the relationship between problem size and running time

My question is, if the input size (problem size of the program) increases, and thus the running time also increases, why would the running time of the program be relatively insensitive to the input? I'm confused.

答:
I think they're not trying to say that the running time doesn't depend on the input size, but rather that it's relatively unlikely to change if you use different inputs of the same size.

For example, a program which inputs n different numbers and calculates the sum of those numbers probably has linear running time, but it shouldn't matter much whether the n numbers are all 0's or some of them are larger than 100 etc.

Title: Running time insensitive to input?


答:
I used to think like your colleague due to some bad experiences I'd had debugging issues related to session variables, which were really just incompetence on my part.  Yes you can get by to some extent without session variables, using query strings, hidden fields in forms and other things.  However it very quickly gets cumbersome to do it this way if your application has anything beyond the most basic logic flow to determine state.  There's also the security risk of showing the inner workings of your application via query strings and hidden fields, any of which can serve as attack vectors.

When working with session variables you just need to keep track of when they get set and unset, as this will determine the logic flow of the application.  It's like memory management in a language like C.

Note that this is just from my experience working with PHP on a relatively small project with no frameworks, things may be different on other platforms but I think the general principle still applies.

Title: Should session variables be avoided?

Body:
I used to heavily rely on session variables in the past, but have recently found many of them to be unnecessary, using things like query string parameters instead.

A colleague of mine refuses to use session variables. Is this a realistic goal and should session variables be avoided for any practical reasons? Can session variables be avoided completely (except for session cookies to allow logins) and would this result in better designs?

Some of the reasons my colleague has for not using them:

Untyped nature of session variables

Session time-outs causing loss of state

Global scope nature of session variables

Load balancing servers losing sessions (.Net specific?)

Application pools/servers restarting

They are unnecessary


问:
Why doesn't Microsoft release UX frameworks to build UI's like their current UIs?
When I started learning programming with the .NET framework, I started by using WinForms as a UI technology. It uses “classic” menus just like this office 2000:

A few years later Office 2007 was released, the ribbon was born:

And even some years later Office 2010 was released, which also added new features like the stage:
A few days ago Office 15 preview was released and they added more fancy new stuff:

That's huge progress IMO, but why don’t they enable the developers to build UI’s like them? When I have a look at .NET, there’s still no way to build a ribbon. Even with WPF, which is highly extensible, there are no premade controls. So the community has started several projects to create all those "features". I know, today Microsoft has released a ribbon for WinForms and WPF, but that's still not part of any core framework (not even the 4.5 one). But this is not limited to .NET as far as I know? Today there are still no APIs for unmanaged applications to create those ribbon UI’s?!

In Germany they are offering free UX training to make sure everything fits their style! http://j.mp/NZGgH9

Why doesn’t Microsoft give the cool stuff to us developers? Do they want their applications to be unique?

答:
Historically, Microsoft has always provided developers with tools to create standard Windows applications (MFC, WinForms, WPF).

The problem here is that Office is being developed by a different group than the one that provides developer tools & frameworks.  This means that when the Office group creates something like the Ribbon or Backstage, the Developer Tools group needs to play catch-up to create a reusable control to provide the functionality.

I also believe there was in-fighting between the two groups that caused such a long delay in the Ribbon being available.  My guess is that the Office group wanted to keep the Ribbon unique to the Office applications and the Developer Tools group wanted to make it available for everyone to use.


问:
Should you use Fields or just Properties in C#?
I've seen some people who make properties for every single member, private or not... does this make any sense?

```<code>private string mWhatever;

private string Whatever
{
    get
    {
        return this.mWhatever;
    }
    set
    {
        this.mWhatever = value;
    }
}
</code>```

I could see it making sense in 1% of the cases at times when you want to control access to the member inside the class containing it.

Because if you don't use properties for every member it would lead to inconsistencies and checking to see if the member has an access or not (since you have access to both in the scope of the class).

答:
Private properties can be very useful to encapsulate the behaviour of things which are internal to your class. Just because they are private doesn't mean that you shouldn't take advantage of the syntactic sugar that properties give you.

The example given is a poor one, however. Boilerplate property getters and setters like this are almost always a bad idea. If you are using C# 3.0 or later then, auto properties are a much better idea:

```<code>private string Whatever { get; set; };
</code>```

This is shorter, cleaner, and much more readable. In fact it is barely longer than just declaring the backing variable.

Most importantly though, auto properties can be converted to full properties at any time without changing the semantics of the rest of the program! Thus if you need to add validation or error handling, you can do so easily.

As it is, I always thought it was a shame that you couldn't have a read only property, to enforce only being able to write to the value in the constructor, (I prefer immutable types) but this was added in C# 6.0 as "Auto-Property Initializers", which allows you to do:

```<code>private string Whatever { get; } = ...;
</code>```

or

```<code>private string Whatever { get; };
</code>```

along with

```<code>    Whatever = ...;
</code>```

in the constructor.

ContentLicense: CC BY-SA 4.0

Body:
Private properties can be very useful to encapsulate the behaviour of things which are internal to your class. Just because they are private doesn't mean that you shouldn't take advantage of the syntactic sugar that properties give you.

The example given is a poor one, however. Boilerplate property getters and setters like this are almost always a bad idea. If you are using C# 3.0 or later then, auto properties are a much better idea:

private string Whatever { get; set; };

This is shorter, cleaner, and much more readable. In fact it is barely longer than just declaring the backing variable.

Most importantly though, auto properties can be converted to full properties at any time without changing the semantics of the rest of the program! Thus if you need to add validation or error handling, you can do so easily.

As it is, I always thought it was a shame that you couldn't have a read only property, to enforce only being able to write to the value in the constructor, (I prefer immutable types) but this was added in C# 6.0 as "Auto-Property Initializers", which allows you to do:

private string Whatever { get; } = ...;

or

private string Whatever { get; };

along with

    Whatever = ...;

in the constructor.


问:
Does following TDD inevitably lead to DI?
I learned to do Test Driven Development (TDD), Dependency Injection (DI) and Inversion of Control (IoC) all at the same time. When I write code using TDD I always end up using DI in my class's constructors. I am wondering if this is because of how I learned to do TDD, or if this is a natural side-effect of TDD.

So my question is this: Does following TDD principals and writing unit tests that do not depend on external services inevitably lead to DI?

答:
Does following TDD and writing unit tests that do not depend on databases or external services inevitably lead to DI?

For wide definitions of DI, yes. Classes do not exist in a vaccuum, so they need to have their dependencies filled somehow. Sometimes just providing a value is fine. Sometimes you need to provide a mock in the constructor. Sometimes via IoC containers. Sometimes via private test accessor. It's all injecting some test thing into the class so it can work in isolation.


问:
What if globals make sense?
I've got a value that many objects need. For example, a financial application with different investments as objects, and most of them need the current interest rate.

I was hoping to encapsulate my "financial environment" as an object, with the interest rate as a property. But, sibling objects that need that value can't get to it.

So how do I share values among many objects without over-coupling my design? Obviously I'm thinking about this wrong.

答: Things should be passed in messages, not read from a global thingy.</p>

Title: What if globals make sense?


问:
What is the relevance of resumes in the age of GitHub, Stack Exchange, Coursera, Udacity, blogs, etc.?
My resume is no longer relevant. It can no longer contain an adequate description of my technical abilities. One can get a much better sense of what I am capable of by looking at my GitHub repositories, my Stack Exchange profiles, and the various courses that I am taking at Udacity and Coursera. The problem is that I have no idea how to tell employers that those are the places to look if they want an accurate description of what I can do.

Every time a recruiter contacts me I gently nudge them towards all the resources I just mentioned and I also provide a link to a publicly visible Google doc that contains my resume along with links to all those resources. Yet, they keep coming back asking for a more descriptive resume.

How can I make it even more blatantly obvious that if somebody wants to hire me then they can save themselves a whole bunch of trouble by just clicking on a few links and browsing around?

答:
The movie superstars, who command multi-million-dollar flat fees to appear in movies, still have resumes with a headshot and recent achievements, which they send to directors/producers when they're interested in a role.

Thus, the first and foremost function of a resume. It tells me you're interested enough in the job to do the work of compiling or tailoring a resume that you think I want to look at. I can cull hundreds of LinkedIn profiles of people whose professional qualifications match the job description of an opening (including geographic location); if unemployment stats of college grads are an indication, only 4 or 5 in 100 have no job and would jump at this, and maybe only 1 or 2 more per hundred would leave their current job to come work for me. It won't be obvious who's who, unless some of those people are contacting me (though LinkedIn or otherwise) with interest in a job.

Tech-savvy features, like URLs to relevant blogs you write, LinkedIn profiles, even your user and rep on StackExchange sites, tell me you know your stuff, and more importantly, tell me exactly where to look. Unfortunately, names, even the combination of first and last, are not unique. Google my name and you find 25 LinkedIn profiles, numerous Facebook accounts, articles about Occupy Oakland and references to a US ambassador, very few of which have anything to do with me. If you tell an interviewer "just Google my name", you better be damn sure the first link is what he wants to see. By contrast, give him the exact URL to your coding blog, give him your exact StackOverflow username so he can look you up, and you have more control by leading him exactly where he needs to go.


答:
If you have a session variable in your application, ask yourself this:

When I click the back button of my browser, what value do I
  want my variable to have?

If the answer is "the current value", session variables may be useful. An example would be a shopping cart: you don't expect things to be removed from the shopping cart as you go back through the history. It's always in its current state.

If the answer is "a previous value", you should not be using session variables. Bad uses I have seen include passing a parameter between pages. If I click the back button to get back to a page, the page does not necessarily get the correct parameter. Also, if I open two tabs, how is my site going to behave then?

Getting the back button behaviour right is by no means the be-all-and-end-all, but it helps you think about a web site as a stateless application. In general, I find appropriate uses of session variables to be few and far between.

Title: Should session variables be avoided?


问:
Choosing the right license for a testing framework
I've finished a first working, releasable version of a testing framework. Prior to release, I want to apply a proper license to it. Normally I'd choose something like GPLv3 but here I am pretty unsure. If I put the testing framework under GPLv3, does that mean users won't be able to test their commercial applications without also putting them under the GPL? Would a license like the MIT be a better fit?

I've just had a look at several popular testing frameworks (JUnit, Jasmine) and none of them uses the GPL.

EDIT

Forgot to mention the project is open sourced.

答:
Firstly it probably doesn't matter. There are a lot of testing frameworks. Almost every company/project/developer seems to roll their own version of cppunit, so the chance of the license you choose actually having any major effect is small.

Secondly GPL limits how you can distribute a derived work. Unless your testing framework requires some changes to my main codebase (in which case it's  a very bad testing framework!) then I should only need to use your code for my unit tests which I'm not going to distribute anyway.


答:
Because the formats were not designed to make things easy for independent software developers, they were designed to make things easy for independent operating system distributors, and RedHat and Debian couldn't care less what format the other is using.  It's sort of like asking why it's so difficult to play Vivaldi on an electric guitar.

That being said, people have tried.  AutoPackage is the most notable I'm aware of.  It doesn't replace the native package manager, but complements it, which is probably why it was more successful than one-ring-to-rule-them-all attempts.  The other thing people commonly use is Alien, which can convert from one format to another.  The other common solution if your most important software is only packaged in one format is simply to switch to the distro that supports that format.

As far as independent software developers are concerned, most take one of three approaches.  Some open source projects just distribute in source format and count on distributions to handle the binary formats.  Closed source software on Linux is usually distributed with some sort of custom bash script installer.  Additionally, open and closed source developers frequently distribute both rpm and deb formats.  It takes maybe one workday to set it all up, then you rarely have to worry about it.  If it wasn't so easy, more people would be clamoring for a change.

Title: Why rpm and deb package formats are not unified into one standard system?


答:
I used not to ask such questions. I answers theirs, I asked one or two classic questions and I would be done.

That was not a good idea.

I'm leaving my current job soon (only two weeks left:) ) and from now I will ask. I might be won't ask directly, but I'll conduct my lesser Joel test (cvs, automating testing, ticket tracker).
If they find offending that I want to evaluate their methods/work: it's not a place I want to work in. IMHO the employer should find it interesting that I want asked, if


问:
Why is OOP difficult?
When I started using an object-oriented language (Java), I pretty much just went "Cool" and started coding. I've never really thought about it until only recently after having read lots of questions about OOP. The general impression I get is that people struggle with it. Since I haven't thought of it as hard, and I wouldn't say I'm any genius, I'm thinking that I must have missed something or misunderstood it.

Why is OOP difficult to understand? Is it difficult to understand?

答:
Regardless which paradigm (OOP, functional, etc.) you choose, in order to write a computer program, you need to know what steps your program will do.

The natural way of defining a process is writing down its steps, for larger tasks you break down the task into smaller steps. This is the procedural way, this is how the computer works, this is how you go through your checklist step by step.

OOP is a different way of thinking. Instead of thinking of a checklist of tasks which needs to be done step by step, you think of objects, their abilities and relationships. So you will write a lot of objects, small methods and your program will magically work. To achieve this, you need to twist your a mind...

And this is why OOP is difficult. Since everything is an object, all they does is asking other objects to do something, and those other objects basically do the some. So the control in an OOP program can wildly jump back and forth between the objects.

Title: Why is OOP difficult?


问:
Fractional and Cartesian Coordinates
I have a set of fractional coordinates.

I also have a rotation matrix that operates on cartesian coordinates.

Does anyone know how I could convert my rotation matrix so I can operate on the fractional coordinates?

The fractional coordinates are functions of the basis vectors a,b,c and the corresponding alpha, beta, gamma.

The following link explains how to do coordinate transformations. I'm just not sure about how to use the listed matrices to operate on the rotation matrix.

http://en.wikipedia.org/wiki/Fractional_coordinates

Any ideas?

Thanks

答:
Looks like you need to do:

Convert Fractal Coordinates -> Cartesian Coordinates (CC1).

Create a Positional Matrix (PM) from your CC1.

Perform the rotation on the PM using your rotation matrix to get a Transformed Matrix (TM).

Get the Cartesian Coordinates (CC2) from TM.

Convert CC2 -> Fractal Coordinates.

Title: Fractional and Cartesian Coordinates


答: I prefer not to have multiple returns in a function.</p>

Title: Not specifying a return in a function, good or bad?

Body:
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?


问:
A place for putting code samples in projects
Every now and then I get or write some minimal code samples to achieve tasks. What's the usual practice for storing these samples (which could prove useful later on) ? Have a separate source folder or create a separate project ?</p>

答: Depending on the size of the creation. For smaller 'mixed' stuff you can have one project called 'bazaar'. But if you have some more complex (but still experimental) code you might want to create one project for each. Example for latter: "spring-mvc-poc" where poc stands for proof of concept.


答:
Lets CF be the matrix "Fractional to Cartesian" and FC be the matrix  "Cartesian to Fractional" (the ones in your Wikipedia article). Let RC be the rotation matrix and  xf be a fractional vector. Then to calculate the rotation, you have to transform xf to cartesian (xc = CF * xf), rotate it (xc_rotated = RC * xc) and transform it back (xf_rotated =  FC * xc_rotated). Put this together and you get

```<code>xf_rotated =  FC * RC * CF * xf
</code>```

So, the matrix you are looking for is FC * RC * CF.

Title: Fractional and Cartesian Coordinates

Body:
I have a set of fractional coordinates.

I also have a rotation matrix that operates on cartesian coordinates.

Does anyone know how I could convert my rotation matrix so I can operate on the fractional coordinates?

The fractional coordinates are functions of the basis vectors a,b,c and the corresponding alpha, beta, gamma.

The following link explains how to do coordinate transformations. I'm just not sure about how to use the listed matrices to operate on the rotation matrix.

http://en.wikipedia.org/wiki/Fractional_coordinates

Any ideas?

Thanks

Body:
Lets CF be the matrix "Fractional to Cartesian" and FC be the matrix  "Cartesian to Fractional" (the ones in your Wikipedia article). Let RC be the rotation matrix and  xf be a fractional vector. Then to calculate the rotation, you have to transform xf to cartesian (xc = CF * xf), rotate it (xc_rotated = RC * xc) and transform it back (xf_rotated =  FC * xc_rotated). Put this together and you get

xf_rotated =  FC * RC * CF * xf

So, the matrix you are looking for is FC * RC * CF.


答:
Yes and no: TDD leads to writing well-structured code, which itself leads to DI.

By that I mean TDD generally sends you the right way with regards to encapsulation, SRP and reusability. It's not just about getting some tests round your code: it's about using those tests to flesh out a better design. If an object creates its own dependencies, then it's living within a specific context within a specific application and is likely to be woven into the application to a greater degree. DI is a good thing, not just from a testing point of view, but also from a code quality point of view.

Title: Does following TDD inevitably lead to DI?

Body:
I learned to do Test Driven Development (TDD), Dependency Injection (DI) and Inversion of Control (IoC) all at the same time. When I write code using TDD I always end up using DI in my class's constructors. I am wondering if this is because of how I learned to do TDD, or if this is a natural side-effect of TDD.

So my question is this: Does following TDD principals and writing unit tests that do not depend on external services inevitably lead to DI?


答:
For people who already know about DI, but just have never seen the point, I think unit testing will almost invariably lead to using DI.

If you don't know about DI and are trying to write unit tests, some people will naturally reinvent DI, some will get frustrated and eventually discover DI through research, but you'd be surprised how often it simply won't occur to someone that there might be a better way to architect their software to make unit testing easier.  Those people write off unit testing as intractable and give up.


答:
As previously stated HTTP is Stateless and Session Variable break that.
HTTP design to be stateless helps caching of resources. For resources that are publicly available.

It's possible to design a website without session variable but it's harder. The hardest (IMHO) is the fancy login/logout, HTTP authentication schemes does not provide the tools needed to authenticate via an HTML form (you might hack something with javascript - XHR to https://untel:passowrd@mydomain.com) and it's even harder to logout and be cross browser compatible. there was some discussion the w3 mailling lists about that but if I remember correctly the idea was dropped.

For the rest, you should be able to live without Session variables. You will have some state on a database, files or anywhere but the use for Session variables should be rare.

If your user have a shopping cart, it's a variable session only if the user is supposed to be able to browse on two computer/browser without sharing the cart.

Title: Should session variables be avoided?


问:
Automation at GUI or API Level in Scrum
I am a Automation Engineer. I use QTP for Automation.
I wanted to know couple of things.

In a scrum Project which has 2 weeks of work, how can complete automation be done in that time frame (talking only about the GUI Level)?

Similarly, how can API Level of automated testing be accomplished, especially inside a single sprint? And what exactly is API level testing?

How to begin with API Testing? I assume QTP is not the tool here certainly.

答:
By breaking up the automation tasks such that they can be completed in a single sprint.

See 1.

Please define API testing. If you're referring to testing interaction of multiple code units (internal and/or external), then you're likely looking at integration testing.

Title: Automation at GUI or API Level in Scrum


问:
Validating best practices, property vs dto, simple type vs object
Consider an application where adds an email address to his profile and submits it.

We have some dispute in our team over how to validate this email address. Some developers (including me) believe that we should validate this simple string via an extension method:

```<code>bool isValid = newEmail.IsEmail();
</code>```

They argue that any validation mechanism other than a single method call would be overhead, and an anti-pattern (against KISS principal).

While others argue that this email should first be added to a new instance of UserEmail DTO, then that DTO should be passed to a the relevant validator:

```<code>UserEmail userEmail = new UserEmail() { Email = newEmail };
bool isValid = new UserEmailValidator().Validate(userEmail);
</code>```

The second group argues that validating a single property makes no sense, because a property can't exist on its own. Thus we should always validate an object, not a property (I mean, value type properties, like strings and integers, etc.)

What advantages and disadvantages could each approach have?

答:
It depends on your validation rules.  Checking for a correctly formatted email address can be a simple method call.  Checking that an email address actually exists, or that it is not already in use somewhere else requires a larger context that usually isn't appropriate as part of a simple field.

Where I disagree on in any case is wrapping it in a DTO instead of just passing the string straight into Validate().  If you eliminate the first line, the second solution suddenly doesn't look so horribly complex.


答:
Others have made a lot of good points (which I will avoid repeating), but there is one aspect of your buddy's technique that has not been discussed yet: security.

Its impossible to know what kind of vulnerabilities you open up without looking at the code, but here's a few things I can think of off the top of my head.

Session fixation: A powerful attack that is slightly easier if you can just have the user click a link that already has the necessary info in the URL (rather than trying to get the user to use a machine that has its cookies appropriately set).

SQL injection (or other malicious input): Never trust anything that comes from the user. Session variables have an advantage of never leaving the server, thus the user cannot directly change them. While you should sanitize data before putting it into the session, you can always trust the values you get out afterwards. If everything is passed around through the query string, you have a LOT of validating you need to do to make sure that you're not accepting malicious input.

Corrupting data by using falsified inputs: Similar to SQL injection, how much data are you passing back and forth? How crucial is it? Can I change the behavior of your app by changing a value in the query string? Can I corrupt the data on your server by changing values? If I manage to corrupt the data on the server, will it affect other users? (If your answer was "no", my response is "are you sure? You have a lot of places you need to check.").

All of these can still happen when you use Sessions, but they can get a lot easier if your buddy doesn't know what he's doing.

Title: Should session variables be avoided?


答:
You don't try to "complete automation". Instead, you have stories just like everyone else. You might have stories strictly for automation, or better, automation is part of the acceptance criteria of a user story.

You are (or should be) part of a team for which automation is part of what is delivered. Your work doesn't stand apart from your team. Together you should decide what you can deliver as a team.

A two-week sprint shouldn't mean "we can write the code in two weeks", but rather "we can write the code and test it in two weeks". If you can't do that in two weeks, either you need simpler stories, better team members, or longer sprints.

As for API testing, pick an appropriate language and start writing code that calls your API.

Title: Automation at GUI or API Level in Scrum

Body:
I am a Automation Engineer. I use QTP for Automation.
I wanted to know couple of things.

In a scrum Project which has 2 weeks of work, how can complete automation be done in that time frame (talking only about the GUI Level)?

Similarly, how can API Level of automated testing be accomplished, especially inside a single sprint? And what exactly is API level testing?

How to begin with API Testing? I assume QTP is not the tool here certainly.


问:
Reverse engineering: what is it really good for?
I have some innocent/beginner questions:

What is reverse engineering good for?

As a programmer, should I learn the art of reverse engineering?

What are the benefits to a programmer who is experienced with it?

答:
What is reverse engineering is good for?

Reverse Engineering is mainly good for cracking and hacking (remove serial number protection or password prompts), but also for understanding viruses or miracles that other softwares can perform. Sometimes it is a useful skill to have in order to find bugs in programs that you haven't got the source for and to patch them.

As a programmer, should I learn the art of reverse engineering?

Yes, try to learn assembler and to use a decent debugger. It will make you a better developer by understanding things on lower levels, that are closer to the metal.

What will be the benefits of a programmer who is well-experienced with
  reverse engineering?

You'll be a good hacker/cracker. You could work for other anti virus producers. As a personal example: I once reverse engineered a software to track down an error that occured while establishing an oracle connection. No one else could solve the problem, so I got some fame.

In addition, I'd also like to cite @johannes comment, as he is absolutely right:

I won't limit it to "bad" cracking. Disassembling can be useful to
  figure out whether the compiler went mad (usually it's your code,
  though), from a more sysadmin point of view it can be interesting to
  see where an application fails


问:
Is There Any Benefit To Participating On Sites Like TopCoder And Or GoogleCode?
Apart from the obvious reasons, like financial, employment and recognition, what are the practical/real benefits to using programming competition sites?

It seems quite algorithmic and maths heavy, but how does that map to something practical, in your everyday programming?

答: It forces you to learn new techniques that you would not have otherwise learned in your day to day ritual. These new learnings can then be turned around and applied to improve your daily rituals.</p>


答:
Merriam-webster defines abstract as an adjective being: disassociated from any specific instance.

An abstraction is a model of some system. They often list a group of assumptions that have to be met for a real system to be able to be modeled by the abstraction, and they are often used to allow us to conceptualize increasingly complicated systems. Going from a real system to an abstraction does not have any formal mathematical method for doing so. That's up to the judgment of whoever is defining the abstraction, and what the purpose of the abstraction is.

Often times though, abstractions are defined in terms of mathematical constructs. That's probably because they are so often used in science and engineering.

An example is Newtonian mechanics. It assumes everything is infinitesimally small, and all energy is conserved. The interactions between objects are clearly defined by mathematical formulas. Now, as we know, the universe doesn't quite work that way, and in many situations the abstraction leaks through. But in a lot of situations, it works very well.

Another abstract model is typical linear circuit elements, resistors, capacitors, and inductors. Again the interactions are clearly defined by mathematical formulas. For low frequency circuits, or simple relay drivers, and other things, RLC analysis works well and provides very good results.  But other situations, like microwave radio circuits, the elements are too big, and the interactions are finer, and the simple RLC abstractions don't hold up. What to do at that point is up to the judgment of the engineer. Some engineers have created another abstraction on top of the others, some replacing ideal op-amps with new mathematical formulas for how they work, others replace ideal op amps with simulated real op-amps, which in turn are simulated with a complex network of smaller ideal elements.

As others have said, it is a simplified model. It is a tool used to better understand complex systems.

Title: What is abstraction?

Body: Is there a generally agreed upon definition for what a programming abstraction is, as used by programmers? [Note, programming abstraction is not to be confused with dictionary definitions for the word "abstraction."] Is there an unambiguous, or even mathematical definition? What are some clear examples of abstractions?


答:
It seems quite algorithmic and maths heavy, but how does that map to something practical, in your everyday programming?

Hopefully by realizing that the important bits of everyday programming is algorithmic and maths heavy. The rest is plumbing to get data from A to B.

Apart from the obvious reasons, like financial, employment and recognition, what are the practical/real benefits to using programming competition sites?

They provide a better metric by which to measure your improvement over time. And practice is always helpful.

Title: Is There Any Benefit To Participating On Sites Like TopCoder And Or GoogleCode?

Body:
Apart from the obvious reasons, like financial, employment and recognition, what are the practical/real benefits to using programming competition sites?

It seems quite algorithmic and maths heavy, but how does that map to something practical, in your everyday programming?


问:
How to create a common interface for classes with different subsets of members
Don't know how to put it, But I'll try to be as clear as possible

I have a project in which I am creating lots of classes and those classes have some common properties and methods but those methods could have different code in them,

So I decided to make an interface so that I could inherit that in all classes and all classes would have same methods in them like insert, update, delete with different code inside those those methods but this trick flopped when I discovered that not all classes have same structure like some have insert method but not update and if I inherit interface I have to provide a public declaration for all members of that interface which I don't want.

Trick two I thought about abstract classes created one too but same problem all the abstract members has to be implemented with public.

So long story short

I want to create a common inheritable structure which would work as a non instance-able blue print for classes and could be inherited into lots of classes but in many classes I don't want to implement all of the members of that structure

NOTE : I can do no-op(empty methods that do nothing, or return a null, for example) as some guys suggested me but that ain't the solution I am looking for because those unnecessary members will be visible during intellisence and that's what i want to avoid.

How can I do that ?

答:
One way to do this is have one interface with the three methods, and implement it in a few abstract classes (these would be the base classes for the full implementations).

These abstract classes would only implement methods that are not needed and would implement them as no-ops (empty methods that do nothing, or return a null, for example).

Your actual implementation classes would inherit from these abstract classes and only implement the needed subset of operations.

Another option is to adhere to ISP (Interface Segregation Principle) and have a number of interfaces - one for each behaviour needed.

Update:

This second option would suit the requirement to not have certain methods show up in IntelliSense. It does, however, mean that you would not be able to use a single inheritance tree, but segregate it (which, from your description of the model, is probably the correct solution).


答:
I like Falcon's answer, but I'd like to add that on some old boring business application world reverse engineering can get you out of some nasty troubles.

At work we do it a lot when doing data integration with a 3rd party system that does not have any new maintenance, so we can know where it should or should not break.

We also use reverse engineer to check code quality (with certain constraints, of course) on 3rd party components we buy, if the source code is not included.

My real point is: reverse engineering is not tied to a single technology or language, but is a process where you learn the internals of a "black box". If you have code you depend on, but you don't or can't trust, you should definitely take a peek under the hood and see what that code is doing.

Title: Reverse engineering: what is it really good for?

Body:
I have some innocent/beginner questions:

What is reverse engineering good for?

As a programmer, should I learn the art of reverse engineering?

What are the benefits to a programmer who is experienced with it?


答: The simple answer is to just create multiple interfaces:  Insertable, Updateable, Deleteable, etc.  However, keep in mind that just because classes have similar methods doesn't mean they need to share an inheritance structure.  You only want to use inheritance when you need to reuse the code that calls it, like if you need  a container that holds a bunch of different objects of different types, and you need to call insert() on everything in that container.

Title: How to create a common interface for classes with different subsets of members

Body:
Don't know how to put it, But I'll try to be as clear as possible

I have a project in which I am creating lots of classes and those classes have some common properties and methods but those methods could have different code in them,

So I decided to make an interface so that I could inherit that in all classes and all classes would have same methods in them like insert, update, delete with different code inside those those methods but this trick flopped when I discovered that not all classes have same structure like some have insert method but not update and if I inherit interface I have to provide a public declaration for all members of that interface which I don't want.

Trick two I thought about abstract classes created one too but same problem all the abstract members has to be implemented with public.

So long story short

I want to create a common inheritable structure which would work as a non instance-able blue print for classes and could be inherited into lots of classes but in many classes I don't want to implement all of the members of that structure

NOTE : I can do no-op(empty methods that do nothing, or return a null, for example) as some guys suggested me but that ain't the solution I am looking for because those unnecessary members will be visible during intellisence and that's what i want to avoid.

How can I do that ?


问:
How do I create my own programming language and a compiler for it
I am thorough with programming and have come across languages including BASIC, FORTRAN, COBOL, LISP, LOGO, Java, C++, C, MATLAB, Mathematica, Python, Ruby, Perl, JavaScript, Assembly and so on. I can't understand how people create programming languages and devise compilers for it. I also couldn't understand how people create OS like Windows, Mac, UNIX, DOS and so on. The other thing that is mysterious to me is how people create libraries like OpenGL, OpenCL, OpenCV, Cocoa, MFC and so on. The last thing I am unable to figure out is how scientists devise an assembly language and an assembler for a microprocessor. I would really like to learn all of these stuff and I am 15 years old. I always wanted to be a computer scientist someone like Babbage, Turing, Shannon, or Dennis Ritchie.

I have already read Aho's Compiler Design and Tanenbaum's OS concepts book and they all only discuss concepts and code in a high level. They don't go into the details and nuances and how to devise a compiler or operating system. I want a concrete understanding so that I can create one myself and not just an understanding of what a thread, semaphore, process, or parsing is. I asked my brother about all this. He is a SB student in EECS at MIT and hasn't got a clue of how to actually create all these stuff in the real world. All he knows is just an understanding of Compiler Design and OS concepts like the ones that you guys have mentioned (i.e. like Thread, Synchronization, Concurrency, memory management, Lexical Analysis, Intermediate code generation and so on)

答:
I was blessed to be exposed to the PDP-8 as my first assembly language.  The PDP-8 had only six instructions, which were so simple it was easy to imagine them being implemented by a few discreet components, which in fact they were.  It really removed the "magic" from computers.

Another gateway to the same revelation is the "mix" assembly language Knuth uses in his examples. "Mix" seems archaic today, but it still has that DE-mystifying effect.

OwnerDisplayName: Dave


答:
What you talk about is polymorphism, which literally means having many shapes.

For example, you might have a base class called Animal, which has a method called Eat(Food food);. Then you might have three classes inheriting from Animal like Dog, Cat, and Hen.

All of these subclasses should have Eat method (by overriding the member of the base class), but each can have its own implementation (doing something differently).

This can be achieved using inheritance by either inheriting from a superclass (base class), or by implementing one or many interfaces (as @Oded said, many small interfaces instead of one big interface).

Another option that comes to my mind is to implementing mixin in C#, but I'm not a pro at it. Just a clue ;).


答: They give you another opportunity to practice. You can practice using different techniques or frameworks. Then when your presented with an opportunity to use these techniques or frameworks in your everyday programming, you will have some experience.</p>


答:
I like sites like TopCoder due to following reason:
 1. Different Approaches for a single problem set: There are multiple ways to solve a problem, it happened with me so many times that i came up with some way to solve a problem and the answer had a better and efficient way to do it. This is the most efficient way to remind you that there are multiple approaches to solve a problem and very useful skill in real life scenarios.

2. Ranking based system and competition takes best out you: When you face the a lot of competition from other guys around world, that certainly makes you better. It Does not matter where you finished but yes you do get motivated. Not all guys go to nice good colleges i know a lot of good self taught programmers who are regular visitor of these sites and they say "Sites like Topcoder satisfy their programming needs".

 You have already mentioned Financial, employment and recognition so i guess these sites are good way to consume knowledge from the internet. I regularly take these challenges as they keep me interested in computer science and programming.


答:
My few cents follow:

1) They are useful to let you satisfy your thirst for knowledge.

2) TopCoder usually hosts competitions from various organizations which pay you for solving real life problems.

3) Usually the problems on TopCoder, GoogleCode, SPOJ etc. are subset of a real world problem, so solving them prepares for any extension of such problems in future.

4) Most importantly, actively participating in them or any such competition (even at work place) keep your brain running and active.


问:
Starting a new project and need ideas for handling Phishing/Brute Force attacks AND Logging access
I'm starting a brand new project.  The main access from the client side app will be via an API written in ASP.Net MVC3.

I'm looking for discussions on how best to handle logging information for security access as well has how to handle Phishing and Brute Force.

On the Information side of things, I'd also like some ideas on what to keep track of to help me both better improve the application in the future and to be able to market it better.

Anyone got any suggestions or links?

答:
Behind good design and good defense lies

Deep Profound Knowledge

So, first of all, I suggest that you read these links as you're not exposed to phishing or brute force attacks and other types of attacks like cookie poisoning, CSRF, form spoofing, HTTP injection, etc. are there waiting for you.

http://www.imperva.com/products/wsc_web-application_attacks.html
http://www.blackhat.com/presentations/bh-asia-02/bh-asia-02-shah.pdf

For logging, I recommend that you use cookie-based authentication, and consider these points for cookies:

Make'em HttpOnly

Make your session cookies session (well, then name says that)

Try to make your cookies secure if possible (SSL, or TLS)

Encrypt your cookie value

Rename your cookie from time to time as the name of a cookie also matters

One of the common patterns to prevent brute force attack is to delay the process by forbidden login intervals, that is, if a user failed to login for say n times, prevent other login requests for say 15 minutes.

Another pattern is to lock user on n times of unsuccessful login retry, and create an unlock mechanism that involves human participation somehow.


答:
There's also the drop-dead boring side of reverse engineering. This is when the company you're at has a bit of code or program that is still being used, but no-one claims to know anything about it. So you go through it, document it, write tests, and all that engineering stuff that should be done before a project is started. You do this for a piece of software that is already written, hence "reverse engineering".

It's a lot easier when you have the code, but it's still technically reverse engineering. It's one of those terms that pops up a lot in business meetings when they're talking about legacy projects.


答:
Unit testing will lead to DI (since it forces you to create loosely coupled units). TDD not necessarily, since TDD can also be used for creating tests layer-by-layer, instead of "verbatim" unit tests. See this article

http://stephenwalther.com/archive/2009/04/11/tdd-tests-are-not-unit-tests.aspx

for an explanation of the differences.


答:
The problem is all your classes have to look alike, because the program using them doesn't know (and doesn't really want to know) which is which.  No-op methods can be a good solution to this problem, but they do have to make sense.  If the calling program calls one, it should not be inconvenienced when it does nothing.

The next step is to have methods that return capabilities, so you don't call methods that a particular object cannot handle.  If CanFly returns false, the caller knows not to call FlyToLA.  This, of course, leaves you with a lot of no-op methods that should never be called--a messy situation at best.

The solution, I think, is to have all your classes/interfaces have a GetFlight method that returns a Flight instance ("Flight" can be a class or interface--interface might work best).  If that method returns null, the object doesn't fly.  If it returns a Flight object, that object contains all the methods concerned with flight, so they are there and available if applicable and nonexistent and unusable if not.

And you'd have other methods, perhaps rather a lot, such as GetDrive, GetAccounting, GetPersonell, etc.  You might even nest them, with the Accounting interface having lot's more "Get" methods for subsets of accounting.  There's a lot of variations on this theme.


问:
How to fix a project with basically no structure?
I've been working on a software project mostly solo for over 5 years. It was a mess to begin with (I am the third or fourth developer to be working on it), and although it's less of a mess now it is still incredibly disorganized. The rate of progress in getting it under control is glacial and I'm starting to feel despondent over the state that it's in. How do I really start fixing it?

Project specifics: It is a sales program written almost entirely in Visual Basic Classic (VB6) with a MySQL back end and a reporting engine written in C#. The C# reporting module is a joy to work on, it was only just written in the past couple years and before that all reports were done in Crystal Reports 9 (yes, we still have some reports that rely on it).

The actual program itself, however, is a complete disaster. There are not quite 90k LOC total, and about 10k lines of comments (mostly not documentation, but old code that's been commented out). 158 form files, and 80 module files. I have no idea how many of those are actually used, because some features of the program are simply deprecated and (uh, sometimes) noted as such without having the associated code removed from the program. I would guess that only 50% of the code is in actual productive use.

I am afraid of touching a lot of the code just because I am not sure if I'm breaking something that one obscure client relies on, it's happened on more occasions than I can count. It's like there are landmines strewn throughout the code.

There is not really any structure to the project. It is not object oriented except in the few places I have had the patience to reform so far. If you need to get data on a form, you instantiate a database object, declare your query right there in the function, execute it and do what you will with the dataset.

When I began working on the project there was no source control in use. I tried to encourage the other people I was working on to use it, but I was the new guy and my attempts to get people to use subversion all but failed. The company's lead developer finally caught a mercurial bug in the last couple years and he's made sure that all developers do use source control on all projects now, so at least that's some progress.

I think if I was able to work on reforming the project full time I would be able to make decent progress and maybe even have an estimate for how long it would take me to fully makeover the project, but it is in active use and I am constantly being asked to put out fires, fix bugs, add features, etc. etc.

So how do I start to really fix this project? Try to tool VB6 with another language? Try and rewrite the program in my spare time? Or is this completely hopeless?

Update

After this post I went back to the project with renewed zeal, but fell back into hopelessness within a few months after seeing such a slow rate of progress. I then repeated this cycle 2 or 3 more times over the next year or so.

I have since moved on to a different job. Although after so many years of vb6, and only peripheral experience with other technologies the search was difficult and I faced many rejections along the way (around a dozen interviews over the course of a year). My advice to others in this situation is to consider leaving for this factor alone. Consider the damage you can do to your career by staying in a dead end position such as this.

答: What you need to do is refactoring. Refactoring is almost impossible in such a situation without unit test that give you the confidence that you haven't broken anything. Therefore, start with creating unit tests. Document the behaviour of the code - but not (only) on paper, but in more code - the unit tests. Once you have the tests in place, you can start restructuring the code.</p>


答:
Now that it's in source control, you can get rid of the commented out code.

I started here in a similar situation (80KLOC VB6 app with no source control, no real structure, almost everything done in event handlers).

In about 2 years on and off I've gotten more than half converted to C# (usually when significant new features are required).  All new C# code has unit test coverage.  It definitely takes way more time to convert to C# though.  If you're not adding significant new modules, I wouldn't go down that route.

One thing I did was create a rudimentary data access layer that auto-generated itself from the database.  That at least caught problems where a table column name changed and I didn't find all the places in the code.  Also, I've slowly moved the business logic into modules, out of the form event handlers.

I, however, had the advantage that the application was only internal.  Since I only had one site to deploy to, I could take some bigger risks than you could.  If I made a mistake, it wasn't usually a big deal to fix it.  Sounds like you don't have that luxury.

I really think your best bet is to take the following approach:

Learn every bit in excruciating detail.  This makes it less likely you'll break something inadvertently.

Refactor mercilessly to improve separation and structure, but don't try to shoehorn a new methodology like object-oriented programming in there, since VB6 just sucks at it.

Treat it as a learning experience.  How would you know a different way is better if you'd never seen the inferior way?

Don't bother rewriting in a new language/framework/platform unless you have a major module to write.  Even then, consider carefully.

Remember, the goal of the program is to be a product that makes your company money.  It doesn't have to be a flawless work of art (and I'm a perfectionist so it's really hard for me to admit that).  Sometimes it's better to embrace pragmatism.

There are supposedly a lot of COBOL programmers out there maintaining massive amounts of legacy code.  I doubt they're all madly working away at rewriting it in some new language.  :)

Title: How to fix a project with basically no structure?

Body:
I've been working on a software project mostly solo for over 5 years. It was a mess to begin with (I am the third or fourth developer to be working on it), and although it's less of a mess now it is still incredibly disorganized. The rate of progress in getting it under control is glacial and I'm starting to feel despondent over the state that it's in. How do I really start fixing it?

Project specifics: It is a sales program written almost entirely in Visual Basic Classic (VB6) with a MySQL back end and a reporting engine written in C#. The C# reporting module is a joy to work on, it was only just written in the past couple years and before that all reports were done in Crystal Reports 9 (yes, we still have some reports that rely on it).

The actual program itself, however, is a complete disaster. There are not quite 90k LOC total, and about 10k lines of comments (mostly not documentation, but old code that's been commented out). 158 form files, and 80 module files. I have no idea how many of those are actually used, because some features of the program are simply deprecated and (uh, sometimes) noted as such without having the associated code removed from the program. I would guess that only 50% of the code is in actual productive use.

I am afraid of touching a lot of the code just because I am not sure if I'm breaking something that one obscure client relies on, it's happened on more occasions than I can count. It's like there are landmines strewn throughout the code.

There is not really any structure to the project. It is not object oriented except in the few places I have had the patience to reform so far. If you need to get data on a form, you instantiate a database object, declare your query right there in the function, execute it and do what you will with the dataset.

When I began working on the project there was no source control in use. I tried to encourage the other people I was working on to use it, but I was the new guy and my attempts to get people to use subversion all but failed. The company's lead developer finally caught a mercurial bug in the last couple years and he's made sure that all developers do use source control on all projects now, so at least that's some progress.

I think if I was able to work on reforming the project full time I would be able to make decent progress and maybe even have an estimate for how long it would take me to fully makeover the project, but it is in active use and I am constantly being asked to put out fires, fix bugs, add features, etc. etc.

So how do I start to really fix this project? Try to tool VB6 with another language? Try and rewrite the program in my spare time? Or is this completely hopeless?

Update

After this post I went back to the project with renewed zeal, but fell back into hopelessness within a few months after seeing such a slow rate of progress. I then repeated this cycle 2 or 3 more times over the next year or so.

I have since moved on to a different job. Although after so many years of vb6, and only peripheral experience with other technologies the search was difficult and I faced many rejections along the way (around a dozen interviews over the course of a year). My advice to others in this situation is to consider leaving for this factor alone. Consider the damage you can do to your career by staying in a dead end position such as this.


答: Not a java guy, but I typically try and put this sample code inside unit tests -- at the very least it can provide a handy way to execute the code to check it out in action.</p>

Title: A place for putting code samples in projects

Body: Every now and then I get or write some minimal code samples to achieve tasks. What's the usual practice for storing these samples (which could prove useful later on) ? Have a separate source folder or create a separate project ?</p>


答:
A quick google search revealed QTP as a GUI robot. Such tools are black box testing tools, testing the compiled binary of the application simulating a user pressing buttons, entering values in some fields, checking the results shown at some other fields etc. Typically, you don't have to know in which programming language the original program was written. Creating such tests typically only makes sense after the GUI parts have reached some level of stability.

When talking of API level tests (as opposed to GUI robot tests), we are talking about white box tests of the GUI logic, not through the GUI elements itself, but through an API layer of the application which is very "close beneath the GUI". Such an API layer is most easily created by applying the "Model-View-Presenter" pattern. This pattern allows testing in a presenter-first approach, which makes it possible to create automatic (unit) tests very early - when doing TDD, earlier than the code for the GUI logic itself. Those tests are typically written by the developers who are writing the presenter, in the same language as the tested application itself, and you typically need only something like a free xUnit testing tool, not more.

To my experience, both kind of testing approaches can test different things. But both approaches can also be used to test a lot of overlapping requirements, in case where I would clearly prefer API level tests (my former experiences with GUI robots were, lets say, a bit disappointing, too much effort for too less benefit). But your mileage will vary.

Concerning Scrum: I have never done that, but I suspect tests using a GUI robot tool are best written after each sprint, while API level tests should be part of the development during the sprint.

Title: Automation at GUI or API Level in Scrum


问:
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?

答:
In C:

```<code>String outputStringForInteger(int i) {
   return (i == 0) ? "Number is Zero" : "Number is not Zero";
}
</code>```

If you insist that the ternary operator is an invention of the Devil, as some do:

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

   if (i == 0) {
      returnString = "Number is Zero";
   } else {
      returnString = "Number is not Zero";
   }
   return returnString;
}
</code>```

Body:
In C:

String outputStringForInteger(int i) {
   return (i == 0) ? "Number is Zero" : "Number is not Zero";
}

If you insist that the ternary operator is an invention of the Devil, as some do:

String outputStringForInteger(int i) {
   String returnString;

   if (i == 0) {
      returnString = "Number is Zero";
   } else {
      returnString = "Number is not Zero";
   }
   return returnString;
}


答:
In .net, if an interface inherits other interfaces, a class which implements the constituent interfaces can be made to be regarded as in implementation of the combined interface simply by declaring it as one, without requiring any extra coding effort.  It could thus be more convenient to have IThis, IThat, and IThisOrThat interfaces than to have one unified "does everything" interface, since classes that can only handle one of the interfaces need not implement stubs for the interface methods they can't handle.  Further, code which needs objects to handle both interfaces at compile time can demand such objects by accepting a parameter of type IThisOrThat.

There are a few limitations with this approach, though:

While it can allow for type-safe code without typecasting, there isn't any remotely-nice way to specify that a collection holds objects which implement multiple interfaces (e.g. {IThis,IThat}) unless all of the types one wishes to use implement a composite interface that includes all the interfaces one needs.  Generics can help a lot with parameters and local variables, but can be less useful with mixed-type collections.

Code may hold objects not just for itself, but also for the purpose of giving them to other code.  Code might accept an object which is required to implement `IThis`, and a delegate which is expected to accept the passed-in object.  If the parameter type of the passed-in object is `IThis`, the code won't be able to pass it to a delegate that expects an `IThisOrThat`, even if the passed-in instance in fact implements the latter interface.  Using generics can help here, but they don't always make things totally smooth.

Sometimes code may have instances whose exact capabilities might vary; in some cases, instances might include methods to produce more capable instances.  For example, an immutable class might have an `AsMutable` function which would return a mutable class instance initialized with data from the immutable one.  It may be more helpful to have fields of type `IMaybeMutableFoo`, which is implemented by both the mutable and immutable classes and includes both "getter" and "setter" methods, than to have the fields of type `IReadableFoo` which includes a getter but no setter and require a typecast any time one wishes to write to the field even after one has tested that the field holds a mutable object.

I like the composite-interface approach, but having semi-composite interfaces (which implement other interfaces, but are not guaranteed to do so usefully) can be useful as well.


答:
Some good answers here already, I would like to add one thing. Instead of trying to rewrite everything, perhaps you will have a chance to port at least some of that modules mostly 1:1 to VB.NET (of course, you have to be very careful either when doing this)? To my experience, such porting can be done with ~5-10 times less effort than trying to rebuild all existing functionality from scratch. And after you have ported it, then you can start to refactor - with all those tools available in the .NET world, like good unit testing tools, automatic refactoring tools, real OOP etc.

I had been in a similar situation, where we had to migrate an old 16 bit C++ program (150k LOC) into the 32 bit world, where the original GUI framework in use was not available any more. It took us some time to understand that rewriting was unrealistic, but after we decided to port that thing to the .NET world, using C++, C++/CLI and C#, we needed only about 9 months to make that happen (with around 1 dev full time working on that project). And we had no unit tests for the GUI part available, did all that testing of those parts manually.


答:
Just to expand on the business value of reverse engineering - more than half of the new customers we encounter have an existing system / app (not always in production, mind you), but where the relationship with a previous software development vendor hit the skids.

In about 30% of the cases the customer hasn't got the source for their system at all, and in many cases, much of the real business process, rules and knowledge is locked away in code.

And in a couple of cases where the previous vendors have gotten plain malicious, obfuscated the binaries, timelocked the code etc in order to ensnare the customer indefinitely.

So to answer your question, reverse engineering is often a starting point for new engagements with rather desperate (and burned) customers, and it can be a 'business critical' success factor to extract forgotten knowledge from existing code.


问:
Multiple javaScript libraries | Emerging standards - compare to C++
It seems like there are many different styles to write JavaScript, in fact I've heard that JavaScript is an expressive language.

But the point of code is functionality (function) not expression (form).

Is there a library that will be adopted into the ECMA standard the way the STL and Boost Library were adopted in to the C++ standard?

答:
But the point of code is functionality (function) not expression
  (form).

This used to be true, but we are finding it evolve in contemporary solutions. First, HTML provides the form. JavaScript is the behavior layer. To that, expressive behavior is a large part of what is requested for rich web applications. In other words, rich and responsive interactions, are behavior; and being able to express them well is a key to the capacity of programmatic implementation. So, expressiveness.

In truth, this term 'expressive' is a synonym for the intangible quality of JS that is also called 'flexibility'. As a voluptuous term, that can mean anything to anyone, 'Expressiveness' has potential to uniquely identify this concept.

Which is a great segway to the first part of your question:

It seems like there are many different styles to write JavaScript,

This is the result of that flexibility and expressiveness.
There are many styles of JS, and (with windows 8, Chrome OS) there will probably be many more.

To find your style: you will have to try a few flavors; it is like ice-cream.

Here is another TIP: the things that look like egyptian heiroglyphs (at first), eventually begin to turn into identifiable patterns. Picking these 'design patterns' out, gives you the ability to understand all styles of JavaScript.

Understanding why JS is flexible and expressive is an exciting journey worth taking.

Hope that helps.


答:
One rule from David Agan's "Debugging" comes to mind:  quit thinking and look.  You happen to have at your disposal a machine capable of processing vast quantities of text.  Use it to figure out precisely what code is no longer in use, and remove it without mercy.  If you make a mistake, that's what source control is for.

That's the easy part.  What you need to think about next is how do you eat an elephant?  One bite at a time.  Pick up Martin Fowler's "Refactoring" and take it function by function, file by file.  Don't completely scrap something and rewrite it from what you think the requirements are.  Work like a mountain climber, never removing your previous safety until the next one is in place.

Had enough metaphors yet?  The point is if you take it slow and steady, with many improvements as simple as renaming or splitting a function, you can improve the bad parts of the code without destroying the good parts of it that were built up through years of debugging and feature requests.  You want the code to remain shippable at all times.  If it's possible to do that while porting to a more modern language, go for it.


答:
I hate to say it but I'd go with "completely hopeless" beyond just continuing to do an endless cycle of patch/enhance and hope nothing breaks. I've seen far too many VB6 projects like the one you describe and attempts to refactor/rewrite/redo them into C#/.NET fail terribly, often with the people in charge of the attempt being fired.

The thing is that an complete rewrite from the ground up is going to be necessary sooner or later. VB6 and Windows versions that support it well are on the decline. Finding developers who know VB6's quirks and who're willing to work on programs like this are becoming rarer. The internal limits of VB6 will be hit on huge programs like this, causing weird errors.

If there's a good consensus and commitment for a total, ground up, redesign and rewrite at this point, begin work on it and delegate ongoing maintenance to someone else (contractors, junior programmers, whatever works for you). If people aren't convinced enough to begin this yet, just wait around for the pain to become great enough or else move on to greener pastures.


问:
Is there a downside to installing Visual Studio Ultimate if I don't need all the features?
Microsoft released today the final builds of Visual Studio 2012 on MSDN. I'm trying to decide from this version comparison page which edition to install (I can install any edition I want for free). I'm a solo developer who develops mostly web apps and console apps in C# and Python. Some of the features in Ultimate/Premium look potentially cool (like UML and "historical debugging"), but most of the features I will not need, or have never heard of.

On the one hand, it would be nice to have the features in case I want them someday. On the other hand, for some software products, the extra features cause the higher end editions to (1) be slower and use more memory, and (2) have a more cluttered UI.

Is this the case with Visual Studio?

答:
The UI is pretty correct in Visual Studio Ultimate. There are more features, especially in the context menu, but those additional features are not too obtrusive. Visual Studio 2010 Ultimate also feels as quick as other versions of Visual Studio 2010.

The main downside is the space it takes both for the ISO and once installed. If you want to install Visual Studio on your SSD which is not very large, this may be an element to encourage you using another edition of Visual Studio.

Given the features which are available only in Visual Studio Ultimate and given the fact that some extensions require the Ultimate version (code contracts static checking was an excellent example in the past; it seems that now, it is available for other versions of Visual Studio too), Visual Studio Ultimate is a good deal, unless you have a very small SSD and don't have money for a larger one.


问:
Best way to load application settings
A simple way to keep the settings of a Java application is represented by a text file with ".properties" extension containing the identifier of each setting associated with a specific value (this value may be a number, string, date, etc..). C# uses a similar approach, but the text file must be named "App.config". In both cases, in source code you must initialize a specific class for reading settings: this class has a method that returns the value (as string) associated with the specified setting identifier.

```<code>// Java example
Properties config = new Properties();
config.load(...);
String valueStr = config.getProperty("listening-port");
// ...

// C# example
NameValueCollection setting = ConfigurationManager.AppSettings;
string valueStr = setting["listening-port"];
// ...
</code>```

In both cases we should parse strings loaded from the configuration file and assign the converted values to the related typed objects (parsing errors could occur during this phase). After the parsing step, we must check that the setting values belong to a specific domain of validity: for example, the maximum size of a queue should be a positive value, some values may be related (example: min < max), and so on.

Suppose that the application should load the settings as soon as it starts: in other words, the first operation performed by the application is to load the settings. Any invalid values for the settings must be replaced automatically with default values: if this happens to a group of related settings, those settings are all set with default values.

The easiest way to perform these operations is to create a method that first parses all the settings, then checks the loaded values and finally sets any default values. However maintenance is difficult if you use this approach: as the number of settings increases while developing the application, it becomes increasingly difficult to update the code.

In order to solve this problem, I had thought of using the Template Method pattern, as follows.

```<code>public abstract class Setting
{
    protected abstract bool TryParseValues();

    protected abstract bool CheckValues();

    public abstract void SetDefaultValues();

    /// <summary>
    /// Template Method
    /// </summary>
    public bool TrySetValuesOrDefault()
    {
        if (!TryParseValues() || !CheckValues())
        {
            // parsing error or domain error
            SetDefaultValues();
            return false;
        }
        return true;
    }
}

public class RangeSetting : Setting
{
    private string minStr, maxStr;
    private byte min, max;

    public RangeSetting(string minStr, maxStr)
    {
        this.minStr = minStr;
        this.maxStr = maxStr;
    }

    protected override bool TryParseValues()
    {
        return (byte.TryParse(minStr, out min)
            && byte.TryParse(maxStr, out max));
    }

    protected override bool CheckValues()
    {
        return (0 < min && min < max);
    }

    public override void SetDefaultValues()
    {
        min = 5;
        max = 10;
    }
}
</code>```

The problem is that in this way we need to create a new class for each setting, even for a single value.
Are there other solutions to this kind of problem?

In summary:

Easy maintenance: for example, the addition of one or more parameters.

Extensibility: a first version of the application could read a single configuration file, but later versions may give the possibility of a multi-user setup (admin sets up a basic configuration, users can set only certain settings, etc..).

Object oriented design.

答:
Are there other solutions to this kind of problem?

If all you need is a simple configuration, I like to make a plain old class for it. It initializes the defaults, and can be loaded from file by the app via the built in serialization classes. The app then passes it around to stuff that needs it. No mussing about with parsing or conversions, no screwing around with config strings, no casting garbage. And it makes the configuration way easier to use for in-code scenarios where it needs to be saved/loaded from server or as presets, and way easier to use in your unit tests.

Title: Best way to load application settings


答:
How I've done it:

Initialize everything to default values.

Parse the file, storing the values as you go.  The places being set are responsible for ensuring the values are acceptable, bad values are ignored (and thus retain the default value.)

Title: Best way to load application settings

Body:
A simple way to keep the settings of a Java application is represented by a text file with ".properties" extension containing the identifier of each setting associated with a specific value (this value may be a number, string, date, etc..). C# uses a similar approach, but the text file must be named "App.config". In both cases, in source code you must initialize a specific class for reading settings: this class has a method that returns the value (as string) associated with the specified setting identifier.

```<code>// Java example
Properties config = new Properties();
config.load(...);
String valueStr = config.getProperty("listening-port");
// ...

// C# example
NameValueCollection setting = ConfigurationManager.AppSettings;
string valueStr = setting["listening-port"];
// ...
</code>```

In both cases we should parse strings loaded from the configuration file and assign the converted values to the related typed objects (parsing errors could occur during this phase). After the parsing step, we must check that the setting values belong to a specific domain of validity: for example, the maximum size of a queue should be a positive value, some values may be related (example: min < max), and so on.

Suppose that the application should load the settings as soon as it starts: in other words, the first operation performed by the application is to load the settings. Any invalid values for the settings must be replaced automatically with default values: if this happens to a group of related settings, those settings are all set with default values.

The easiest way to perform these operations is to create a method that first parses all the settings, then checks the loaded values and finally sets any default values. However maintenance is difficult if you use this approach: as the number of settings increases while developing the application, it becomes increasingly difficult to update the code.

In order to solve this problem, I had thought of using the Template Method pattern, as follows.

```<code>public abstract class Setting
{
    protected abstract bool TryParseValues();

    protected abstract bool CheckValues();

    public abstract void SetDefaultValues();

    /// <summary>
    /// Template Method
    /// </summary>
    public bool TrySetValuesOrDefault()
    {
        if (!TryParseValues() || !CheckValues())
        {
            // parsing error or domain error
            SetDefaultValues();
            return false;
        }
        return true;
    }
}

public class RangeSetting : Setting
{
    private string minStr, maxStr;
    private byte min, max;

    public RangeSetting(string minStr, maxStr)
    {
        this.minStr = minStr;
        this.maxStr = maxStr;
    }

    protected override bool TryParseValues()
    {
        return (byte.TryParse(minStr, out min)
            && byte.TryParse(maxStr, out max));
    }

    protected override bool CheckValues()
    {
        return (0 < min && min < max);
    }

    public override void SetDefaultValues()
    {
        min = 5;
        max = 10;
    }
}
</code>```

The problem is that in this way we need to create a new class for each setting, even for a single value.
Are there other solutions to this kind of problem?

In summary:

Easy maintenance: for example, the addition of one or more parameters.

Extensibility: a first version of the application could read a single configuration file, but later versions may give the possibility of a multi-user setup (admin sets up a basic configuration, users can set only certain settings, etc..).

Object oriented design.