问:
What alternatives are there for cross cutting concerns other than aspect oriented programming?
Aspect oriented programming promises to deal with cross cutting concerns, but I'm not completely sold on it yet. Have there been any other attempts to deal with this problem?</p>

答:
There are several ways to tackle the problems of crosscutting concerns:

Use Better Design Patterns, Idioms, or Abstraction Mechanisms: Code may be crosscutting even though it can be modularized. In order to maintain the code, you will need to refactor to use the design technique that can modularize it. Such refactoring may introduce crosscutting of a different kind, but hopefully what crosscuts is stable, and not likely to change.

Develop Richer Language Features: Many manifestations of crosscutting can be solved through better abstraction mechanisms, and sometimes new language features are necessary. For instance, more advanced languages that include functional and object-oriented features often don't employ as many design patterns, because they aren't necessary. Note that design patterns themselves can be crosscutting in nature, because they describe the roles of several different objects and classes. In Java, reflection can often be used instead of an aspect, although at a higher runtime cost. For example, using reflection, you can support the visitor pattern over hundreds of classes with just a couple lines of code. The DJ library from Northeastern is one reflective solution that does just that. Mixins are a powerful technique available in C++ (but not Java) and can give you some of the same uses cases as an aspect.

Provide Better Tool Support: Techniques such as using grep and performing refactoring operations can deal with problems related to crosscutting code. For example, the name of a method declared in an interface can cut across the program. (Note the technical difference here: It is the name of the method, not the method's implementation, that crosscuts.) This usually isn't a problem in an IDE like Eclipse, where you can use the "rename refactoring" to change all of the places in your code that use the name. In this way, it's possible to not need language features when the programming environment is expressive enough for you.

Use Domain-Specific Languages: The early aspect languages, which came before AspectJ, were domain-specific and applied to only certain problems, such as thread synchronization or data-flow analysis for efficiently combining function compositions. These languages were experimental, but seemed highly successful at modularizing concerns that otherwise were crosscutting.

Use Generative Programming Techniques: Stepping up to the meta level might be considered an implementation technique for aspect-oriented programming, but it's a big enough area that it transcends simple aspects. Generative techniques (where a program generates source code for another program) are also related to domain-specific languages.

For all of these, I think studying AOP is appropriate. AOP can help you expand your conceptions of code, even if you don't use an AOP language.


问:
When should I backup files?
At our company we are not using a source control so we do backup manually.

My habit is like this: I backup only scripts where I removed code snippets, and those scripts where I only added code snippets I don't backup.

Is it reasonable to backup each time when you change something, or there are some conditions for file subversion? And when we backup changed files, should we only backup that file or all the project?

答:
Use modern source control.

Use a Distributed Version Control System like Mercurial or git (over using svn).

It seems intimidating but given that you can do

sudo apt-get git or sudo apt-get install git-core git-gui git-doc

cd your_dir

git init

See http://help.github.com/linux-set-up-git/ for more info

Why not do it now?

For backups I would store this code on github - https://github.com/

ContentLicense: CC BY-SA 3.0

Title: When should I backup files?


问:
Information about how much time in spent in a function, based on the input of this function
Is there a (quantitative) tool to measure performance of functions based on its input?

So far, the tools I used to measure performance of my code, tells me how much time I spent in functions (like Jetbrain Dottrace for .Net), but I'd like to have more information about the parameters passed to the function in order to know which parameters impact the most the performance.

Let's say that I have function like that:

```<code>int myFunction(int myParam1, int myParam 2) {
  // Do and return something based on the value of myParam1 and myParam2.
  // The code is likely to use if, for, while, switch, etc....
}
</code>```

If would like a tool that would allow me to tell me how much time is spent in myFunction based on the value of myParam1 and myParam2.

For example, the tool would give me a result looking like this:

```<code>For "myFunction" :
 value   |  value   | Number of | Average
myParam1 | myParam2 |   call    | time
---------|----------|-----------|--------
   1     |    5     |   500     | 301 ms
   2     |    5     |   250     | 1253 ms
   3     |    7     |   1268    | 538 ms
...
</code>```

That would mean that myFunction has been call 500 times with myParam1=1 and myParam2=5, and that with those parameters, it took on average 301ms to return a value.

The idea behind that is to do some statistical optimization by organizing my code such that, the blocs of codes that are the most likely to be executed are tested before the one that are less likely to be executed.

To put it bluntly, if I know which values are used the most, I can reorganize the if/while/for etc.. structure of the function (and the whole program) to optimize it.

I'd like to find such tools for C++, Java or.Net.

Note: I am not looking for technical tips to optimize the code (like passing parameters as const, inlining functions, initializing the capacity of vectors and the like).

答:
I doubt you'll find such tool, therefore most likely you'll have to implement your own.

However, there are code profilers (for example callgrind to profile c and c++ code), which provides you with some value which represents a relative time spent in a function.


问:
How to gain experience?
This is a problem that I think many people will find very common and some guidance from the expert users around here will be appreciated.

Background

Basically I'm a junior web developer in a team of 6 (all juniors too). 6 months ago our team leader and project manager left the company. Currently we are being managed by a non technical person.

The new manager chose me to act as a technical leader for the rest of the team till the company hires a someone more experienced.

Problem

Although I'm a good developer my experience in providing solution to the company's needs is somewhat lacking. I mean I have no problem implementing solutions or adding new modules to the system as I have been working for 2 years already in PHP and MySql.

The problem is when we are designing a new heavy feature or building a critical module that can't tolerate trial and error.

Check this link for a design issue that I recently had to implement:
https://stackoverflow.com/questions/10529459/building-a-cron-job-scheduler

I can easily build all solutions that were mentioned in the post. The only problem is that I don't have enough experience to choose one of them. My ex-Team leader used to make the hard decisions and I really used to learn a lot from him. However, now he's gone and I'm left out all alone.

Solution

Now There is 2 solutions that I figured would be best for me:

Leave the company ASAP :D and find a better company that can provide me with good experience and increase my knowledge (Although I can't leave the company any time soon due to various reasons).

Find books, references or any available materials for large scale projects or pro web developers techniques. Basically anything beyond simple applications. This is the only option I have right now.

Notes:

I am not looking for resources to learn PHP, MySql, frameworks, ORMs or design patterns. I want knowledge transfer from experienced programmers.

答:
I'm with Simon but I feel that it is important to add:

Lean on your team a bit. I'm willing to bet that there's at least 6-10 years worth of experience in the group. They say that good leaders surround themselves with smarter people than they are. This is one of the reasons why.

So, for your example, you could approach it like this:

Investigate potential solutions.

Ask the team if anyone has written one of the solutions before, ask for a quickie post-mortem and if they were aware of the other solutions and had an opinion.

Ask the rest of the team what they think.

Have a dev POC/Prototype the most promising solutions.

Pick the better one based on your needs and the feedback from the dev(s) that wrote the POCs.

And to be honest, 1-3 takes 15 mins in a daily dev meeting.

Title: How to gain experience?


答: Although such a tool could be very helpful, I'm not aware of any that offer line-based hotspot analysis. Since profilers are tricky to hack and easy to get wrong, you are probably certainly better off temporarily splitting your code into different functions just so a normal profiler can tell you what you need to know.</p>

Title: Information about how much time in spent in a function, based on the input of this function

Body:
Is there a (quantitative) tool to measure performance of functions based on its input?

So far, the tools I used to measure performance of my code, tells me how much time I spent in functions (like Jetbrain Dottrace for .Net), but I'd like to have more information about the parameters passed to the function in order to know which parameters impact the most the performance.

Let's say that I have function like that:

```<code>int myFunction(int myParam1, int myParam 2) {
  // Do and return something based on the value of myParam1 and myParam2.
  // The code is likely to use if, for, while, switch, etc....
}
</code>```

If would like a tool that would allow me to tell me how much time is spent in myFunction based on the value of myParam1 and myParam2.

For example, the tool would give me a result looking like this:

```<code>For "myFunction" :
 value   |  value   | Number of | Average
myParam1 | myParam2 |   call    | time
---------|----------|-----------|--------
   1     |    5     |   500     | 301 ms
   2     |    5     |   250     | 1253 ms
   3     |    7     |   1268    | 538 ms
...
</code>```

That would mean that myFunction has been call 500 times with myParam1=1 and myParam2=5, and that with those parameters, it took on average 301ms to return a value.

The idea behind that is to do some statistical optimization by organizing my code such that, the blocs of codes that are the most likely to be executed are tested before the one that are less likely to be executed.

To put it bluntly, if I know which values are used the most, I can reorganize the if/while/for etc.. structure of the function (and the whole program) to optimize it.

I'd like to find such tools for C++, Java or.Net.

Note: I am not looking for technical tips to optimize the code (like passing parameters as const, inlining functions, initializing the capacity of vectors and the like).


问:
iOS object instance accessible from three separate classes, or load 3 nib files with one class?
I've got three nib files in my project, each of which is driven by its own class (.h and .m files).   Each nib has a stylized design with a full screen background image and a few overlay images acting as buttons.  Each button has its own button-click sound, and most of the buttons on each nib file will play a different video per button.

To play the videos, each of my three .m files have a couple of methods similar to this:

```<code>-(IBAction) videoButtonClicked: (id)sender{
    if([sender tag] == 1) {
        AudioServicesPlaySystemSound (buttonClick1);
        [self loadMoviePlayer:[[NSBundle mainBundle] pathForResource:@"Video 1" ofType:@"mov"]];
    } else if ([sender tag]  == 2) {
        AudioServicesPlaySystemSound (buttonClick2);
        [self loadMoviePlayer:[[NSBundle mainBundle] pathForResource:@"Video 2" ofType:@"mov"]];
    } else if ([sender tag]  == 3) {
        AudioServicesPlaySystemSound (buttonClick3);
        [self loadMoviePlayer:[[NSBundle mainBundle] pathForResource:@"Video 3" ofType:@"mov"]];
    } else if ([sender tag]  == 4) {
        AudioServicesPlaySystemSound (buttonClick4);
        [self loadMoviePlayer:[[NSBundle mainBundle] pathForResource:@"Video 4" ofType:@"mov"]];
        }
}

- (void)loadMoviePlayer:(NSString*) movieURL
{
    // Play movie from the bundle
    NSURL *url = [NSURL fileURLWithPath:movieURL];

    player = [[MPMoviePlayerViewController alloc]
              initWithContentURL:url];

    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(movieFinishedCallback:)
     name:MPMoviePlayerPlaybackDidFinishNotification
     object:player];

    [self presentMoviePlayerViewControllerAnimated:player];
    [player release];
}
</code>```

My code works now because the videos are embedded in my resources folder.

However, together, the videos are too big to be bundled with the app and downloaded from the App Store.

I'll therefore have the app download them from a server, so I want to create one video-management class to keep track of which videos have been downloaded.  I think I should have one instance of the object, but then how can my three controllers talk to the one instance?

I am pretty sure if I have one class that loads the correct .nib file, I can have that one instance talk to my one video-management instance.

But would I be unnecessarily wasting memory by loading all three nibs at once?

答:
You could provide each view controller with a property that is your movie store. Then you can configure each view controller to use the same object:

if it appears as the result of a transition from a different view controller, the previous controller can pass its movie store to the new controller.

the first view controller can receive the configured movie store from either its NIB file or from the app delegate, which is ultimately responsible for configuring the window and therefore for getting the first view controller ready to be displayed.


答:
Your unit tests should cover this. Wrap the calls in a stopwatch and you're good to go.

I'll assume that you don't have any then, so here's one way to get quickly up to speed and get some.

Write a parameterized unit test around your function using Pex and then run that/those tests. Have ANTS running when you do - or just set a stopwatch before/after the call to the function.

Essentially, if I remember correctly, Pex uses a theorem prover to reach every branch and potential exception/boundary condition using the parameters to the function. Check the parameters it comes up with, critically think about some of your own and you should have what you're looking for.


问:
Why is 80 characters the 'standard' limit for code width?
Why is 80 characters the "standard" limit for code width? Why 80 and not 79, 81 or 100? What is the origin of this particular value? </p>

答:
I'd say that's also because old terminals were (mostly) 80x24 characters in size: Back in the days of 80x24 terminals...

EDIT:

To answer more precisely and more thoroughly to the question, 80 characters is the current "universally accepted" limit to code width inside editors because 80x24 and 80x25 formats were the most common screen modes in early I/O terminals and personal computers (VT52 - thanks to Sandman4).

This limit is still valid and somehow important IMHO for two main reasons: the default geometry that many Linux distros assign to newly spawned terminal windows is still 80x24 and many people use them as-is, without resizing. Moreover, kernel, real-time and embedded programmers often work in a "headless" environment without any window manager. Again, the default screen resolution is often 80x24 (or 80x25), and, in these situations, it may even be difficult to change this default setting.

So if you are a kernel, real-time or embedded programmer you should force yourself to respect this limit, just to be a little more "friendly" towards any programmer that should read your code.


答:
If you want to profile just one function, and you know the small number of input combinations you are interested in, you can add some kind of "switch mechanism" which will make the calls visible in any typical profiler:</p>

```<code>int myFunction_internal(int myParam1, int myParam 2) {
  // the main body
}

int myFunction_p1_p5() {
    return myFunction_internal(1,5);
}

int myFunction_p2_p5() {
    return myFunction_internal(2,5);
}

int myFunction_other(int myParam1, int myParam2) {
    return myFunction_internal(myParam1,myParam2);
}

int myFunction(int myParam1, int myParam2) {
   if(myParam1==1 && myParam2==5)
        return myFunction_p1_p5();
   if(myParam1==2 && myParam2==5)
        return myFunction_p2_p5();
   return myFunction_other(myParam1,myParam2);
}
</code>```

Body:
If you want to profile just one function, and you know the small number of input combinations you are interested in, you can add some kind of "switch mechanism" which will make the calls visible in any typical profiler:

int myFunction_internal(int myParam1, int myParam 2) {
  // the main body
}

int myFunction_p1_p5() {
    return myFunction_internal(1,5);
}

int myFunction_p2_p5() {
    return myFunction_internal(2,5);
}

int myFunction_other(int myParam1, int myParam2) {
    return myFunction_internal(myParam1,myParam2);
}

int myFunction(int myParam1, int myParam2) {
   if(myParam1==1 && myParam2==5)
        return myFunction_p1_p5();
   if(myParam1==2 && myParam2==5)
        return myFunction_p2_p5();
   return myFunction_other(myParam1,myParam2);
}


问:
Testing a file that relies heavily on a static array
I have a .c file that basically manages its own little database of people. There are add, remove, edit and search functions among some others. It has a static array which it uses to store the data.

What is a good way to go about unit testing a file like this? Because the array is static I can't put in my own data.

Should I employ some trickery and make a function that passes out a pointer to the array that gets compiled out in the production version? Should I just test the functions as is and make the data they way I want it via a series of adds and removes? What is the best way to test a file like this?

答:
you can refactor you code like this

old code

```<code>   static MyType[] myArray = ...
   void oldFuncThatUsesStaticArray(Type param1, Type param2, Type param3, ...)
   {
      // ... do the processing by accessing global static myArray
   }
</code>```

new code

```<code>   static MyType[] myArray = ...
   void oldFuncThatUsesStaticArray(Type param1, Type param2, Type param3, ...)
   {
      newFuncWithArrayParameter(param1, param2, param3, ..., myArray);
   }

   void newFuncWithArrayParameter(Type param1, Type param2, ..., MyType[] myArray)
   {
      // ... do the processing by accessing the parameter myArray
      // ... that hides global static myStaticArray
   }
</code>```

for the testing you call newFuncWithArrayParameter() while your app is still using oldFuncThatUsesStaticArray()

Note this is pseudo-syntax as i am not a c-developper

Body:
you can refactor you code like this

old code

   static MyType[] myArray = ...
   void oldFuncThatUsesStaticArray(Type param1, Type param2, Type param3, ...)
   {
      // ... do the processing by accessing global static myArray
   }

new code

   static MyType[] myArray = ...
   void oldFuncThatUsesStaticArray(Type param1, Type param2, Type param3, ...)
   {
      newFuncWithArrayParameter(param1, param2, param3, ..., myArray);
   }

   void newFuncWithArrayParameter(Type param1, Type param2, ..., MyType[] myArray)
   {
      // ... do the processing by accessing the parameter myArray
      // ... that hides global static myStaticArray
   }

for the testing you call newFuncWithArrayParameter() while your app is still using oldFuncThatUsesStaticArray()

Note this is pseudo-syntax as i am not a c-developper


问:
Monopoly game 3D graphical interface
I have created a Monopoly game with a 2D Graphics in Java for my final exam at college.

I feel that the game doesn't look very good and I want to add a 3D Graphics. My problem is that I have never done 3D programming and I don't know how to create 3D objects.

Can someone tell me where can I create 3D objects and what library to use for 3D programming that will allow me to create a 3D graphic interface fast? I have only two more weeks to do this. Can this be done?

答:
I agree with the other posters here - you most probably are not going to be able to implement both the code/engine for your game and the 3D content needed in 2 weeks.

However, if the operational part of your question is "I feel that the game doesn't look very good and I want to add a 3D Graphics." then you may not need to implement a 3D engine at all in your game.

Back in the 80s and 90s, before video cards were considered standard hardware in computers, most "true" 3D games that rendered 3D on-the-fly (in software) displayed 3D as wireframes, and later flat, low-count polygons - this wasn't because people didn't know how to make "nicer" 3D graphics - the machines at the time just weren't powerful enough.

Most games were actually 2D, but used various approaches to "fake" a 3D look.

Using isometric graphics is one approach.

Another approach was create 3D models, but instead of creating a 3D engine for the game and loading/animating the model on-the-fly - pre-render graphics of them (probably using a raytracing program) into a series of images that can be animated. (i.e. pre-render the model at various angles, or at various phases of a walking animation and just string the images together.)  This can be combined with the isometric approach mentioned above.

You may be able to use these ideas to make a "better looking"/"fake" 3D version of your game in the 2 weeks you mentioned - I still think it's going to be a tight schedule, but probably more do-able than learning real 3D programming and figuring out how to use a 3D modeling tool and generating 3D models for your game.

Title: Monopoly game 3D graphical interface


问:
Linking in code comments (to other unique anchors/comments)
How would you recommend creating "anchors" in code comments, so that during maintenance, developers can easily cross-reference other code comments.

I realise that software should be intelligently structured and this should mitigate this requirement to some degree, but I have often found myself writing a comment where I would like future developers to take something else into account (not necessarily a direct dependency).

For example, "If you change this mechanism, be sure to review XYZ". I'm thinking of hyper links, wiki-style, where each link has a unique identifier and can have a one-to-many relationship with other links.

Ideally, if someone re-writes some of my code, I would like them to be automatically warned that "something else links here, and you should check it out in case you're changing this" - and I don't mean breaking something as in "something won't compile", but really just an easy-to-follow pointer (or pointers) to somewhere else in a code base that someone (or indeed your past self) felt there was a human-understandable conceptual link, concept or implementation.

I would be surprised if there isn't already a standard in place for this, but searching for "comment", "link", "anchor" understandably yields a proverbial haystack.

答: If you're working in Java, you can create hyperlinks in the Javadoc, though I don't know of any IDEs that take advantage of this as opposed to parsing the code to determine what classes are linked together. See the documentation} for details, and this recommendation for when not to use them.


问:
Is this awkward spacing some type of style?
In reading another programmers code, he uses a format I have never seen.  E.G.

```<code>    namespace MyNs.HereWeAre
         {//tab here for some reason
         public class SomeClass
               {//here's another tab
               public string Method()
                    {//yet another tab
                    string _variable = "";//no tab implementation
                    return _variable;
                    }
               }//eof - class  (Yes these eof comments are on every file)
        }//eof - namespace
// eof - file
</code>```

I'll admit...this code makes me angry.  It is difficult to achieve this style.  One needs to fight the default formatting provided by the IDE, visual studio.

I could swallow this pill a little easier if I knew that there was a good reason for this style.  Does this style stem from some other programming language/IDE?

答:
Yes: http://en.wikipedia.org/wiki/Indent_style#Whitesmiths_style

The Whitesmiths style, also called Wishart style to a lesser extent, is less common today... It was originally used in the documentation for the first commercial C compiler, the Whitesmiths Compiler. It was also popular in the early days of Windows, since it was used in three influential Windows programming books, Programmer's Guide to Windows by Durant, Carlson & Yao, Programming Windows by Petzold, and Windows 3.0 Power Programming Techniques by Norton & Yao...

This style puts the brace associated with a control statement on the next line, indented. Statements within the braces are indented to the same level as the braces...

The advantages of this style are similar to those of the Allman style in that blocks are clearly set apart from control statements. However with Whitesmiths style, the block is still visually connected to its control statement instead of looking like an unrelated block of code surrounded by whitespace. Another advantage is that the alignment of the braces with the block emphasizes the fact that the entire block is conceptually (as well as programmatically) a single compound statement. Furthermore, indenting the braces emphasizes that they are subordinate to the control statement.

A suggested disadvantage of this style is that the ending brace no longer lines up with the statement it conceptually belongs to. However, the closing brace belongs to the opening brace and not to the control statement...

It's one I've never seen practiced though, thank IPU.

Eclipse has a built in Whitesmith code style for c++...you might be screwed with Java since everyone is supposed to use the same style in that language.


答: C# already implements XML Documentation Comments - some of the elements allow you to reference other types and depending on how you produce the documentation they will be links.</p>

Title: Linking in code comments (to other unique anchors/comments)

Body:
How would you recommend creating "anchors" in code comments, so that during maintenance, developers can easily cross-reference other code comments.

I realise that software should be intelligently structured and this should mitigate this requirement to some degree, but I have often found myself writing a comment where I would like future developers to take something else into account (not necessarily a direct dependency).

For example, "If you change this mechanism, be sure to review XYZ". I'm thinking of hyper links, wiki-style, where each link has a unique identifier and can have a one-to-many relationship with other links.

Ideally, if someone re-writes some of my code, I would like them to be automatically warned that "something else links here, and you should check it out in case you're changing this" - and I don't mean breaking something as in "something won't compile", but really just an easy-to-follow pointer (or pointers) to somewhere else in a code base that someone (or indeed your past self) felt there was a human-understandable conceptual link, concept or implementation.

I would be surprised if there isn't already a standard in place for this, but searching for "comment", "link", "anchor" understandably yields a proverbial haystack.


答:
As oded mentioned, this common coding standard is a result of the IBM's 1928 80 column punched card format, since many coding standards date back to a time when programs were written on punch cards, one card/line at a time, and even the transition to wider screens didn't alter the fact that code gets harder to read the wider it becomes.

From the wikipedia page on punched cards:

Cultural Impact

A legacy of the 80 column punched card format is that a display of 80 characters per row was a common choice in the design of character-based terminals. As of November 2011 some character interface defaults, such as the command prompt window's width in Microsoft Windows, remain set at 80 columns and some file formats, such as FITS, still use 80-character card images.

Now the question is, why did IBM chose 80 column cards in 1928, when Herman Hollerith had previously used 24 and 45 column cards?

Although I can't find a definitive answer, I suspect that the choice was based on the typical number of characters per line of typewriters of the time.

Most of the historical typewriters I've seen had a platen width of around 9 inches, which corresponds with the standardisation of paper sizes to around 8"-8.5" wide (see Why is the standard paper size in the U.S. 8 ½" x 11"? and the History of ISO216 A series paper standard).

Add a typical typewriter pitch of 10-12 characters per inch and that would lead to documents with widths of between 72 and 90 characters, depending on the size of the margins.

As such, 80 characters per line would have represented a good compromise between hole pitch (small rectangular vs. larger round holes) and line length, while maintaining the same card size.

Incidentally, not everywhere specifies an 80 character line width in their coding standards. Where I work has a 132 character limit, which corresponds to the width of typical wide line printers of yore, a 12pt landscape A4 printout and the typical line width remaining in an editor window of Eclipse (maximised on a 1920x1200 screen) after Package Explorer and Outline views are taken into account.

Even so, I still prefer 80 character wide code as it it makes it easier to compare three revisions of a file side-by-side without either scrolling sideways (always bad) or wrapping lines (which destroys code formatting). With 80 character wide code, you only need a 240 character wide screen (1920 pixels at 8 pixels per character) to see a full three-way-merge (common ancestor, local branch and remote branch) comfortably on one screen.

Title: Why is 80 characters the 'standard' limit for code width?

Body: Why is 80 characters the "standard" limit for code width? Why 80 and not 79, 81 or 100? What is the origin of this particular value? </p>


答:
In C++, if this is for just a particular method with particular inputs, it's pretty easy to write a helper class that will time how long it takes to execute a particular scope.  You grab the time in the constructor and in the destructor you calculate the current time and save it in a static data structure.

This is a technique I've used with embedded devices for which I had no profiler.

Beware: I haven't compiled/tested this:

```<code>typedef std::map<std::pair<int,int>, std::pair<int,int> > timeMap;

class TimeIt {
private:
    static timeMap times;
    clock_t timeCalled;
    int myParm1;
    int myParm2;

public:
    TimeIt(int parm1, int parm2) : timeCalled(clock()), myParm1(parm1), myParm2(parm2) {}

    ~TimeIt() {
        clock_t runtime = clock() - timeCalled;
        if(timeMap::iterator it = times.find(std::pair<int,int>(myParm1,myParm2))) {
            it->second->first++;
            it->second->second+=runtime;
        }
        else {
            times[std::pair<int,int>(myParm1,myParm2)] = std::pair<int,int>(1,runtime);
        }
    }

    static void report() {
        for(timeMap::iterator it=times.begin();it!=times.end();it++) {
             cout << it->first->first << " | ";
             cout << it->first->second << " | ";
             cout << it->second->first << " | ";
             cout << (it->second->second/it->second->first) << endl;
        }
    }
}
</code>```

Then in your method, do:

```<code>int myFunction(int myParam1, int myParam 2) {

    TimeIt timeIt;

    // Do and return something based on the value of myParam1 and myParam2.
    // The code is likely to use if, for, while, switch, etc....
}
</code>```

And when you want the data:

```<code>TimeIt::report();
</code>```

I'm sure you can do something similar in .NET or Java.  The most important bit is to take care when you grab the clock() time.  You don't want to do anything of significance in the destructor before grabbing the clock() time.

Obviously if you want a more general solution, you want a real profiler.

Body:
In C++, if this is for just a particular method with particular inputs, it's pretty easy to write a helper class that will time how long it takes to execute a particular scope.  You grab the time in the constructor and in the destructor you calculate the current time and save it in a static data structure.

This is a technique I've used with embedded devices for which I had no profiler.

Beware: I haven't compiled/tested this:

typedef std::map<std::pair<int,int>, std::pair<int,int> > timeMap;

class TimeIt {
private:
    static timeMap times;
    clock_t timeCalled;
    int myParm1;
    int myParm2;

public:
    TimeIt(int parm1, int parm2) : timeCalled(clock()), myParm1(parm1), myParm2(parm2) {}

    ~TimeIt() {
        clock_t runtime = clock() - timeCalled;
        if(timeMap::iterator it = times.find(std::pair<int,int>(myParm1,myParm2))) {
            it->second->first++;
            it->second->second+=runtime;
        }
        else {
            times[std::pair<int,int>(myParm1,myParm2)] = std::pair<int,int>(1,runtime);
        }
    }

    static void report() {
        for(timeMap::iterator it=times.begin();it!=times.end();it++) {
             cout << it->first->first << " | ";
             cout << it->first->second << " | ";
             cout << it->second->first << " | ";
             cout << (it->second->second/it->second->first) << endl;
        }
    }
}

Then in your method, do:

int myFunction(int myParam1, int myParam 2) {

    TimeIt timeIt;

    // Do and return something based on the value of myParam1 and myParam2.
    // The code is likely to use if, for, while, switch, etc....
}

And when you want the data:

TimeIt::report();

I'm sure you can do something similar in .NET or Java.  The most important bit is to take care when you grab the clock() time.  You don't want to do anything of significance in the destructor before grabbing the clock() time.

Obviously if you want a more general solution, you want a real profiler.


答:
Scroll in printers papers were Letters size or 15" wide.

It were the 80 cps line printers for hardcopying of codes or reports, and later on Epson supports 132 cps condensed printing (escape code \015 for condensed print).


答:
Whilst your colleague's coding style is bizarre, ugly and hard to read:

if you don't have coding standards, then their formatting is as valid as any.

if you reformat their code every time you touch a file written by them, you'll find it very difficult to track changes - if you perform a diff using your VCS, then many if not all lines of code will have changed.

This is why you should have coding standards, it makes it easier for everyone to know what they should be doing and easier to justify reformatting if they haven't stuck to it.

If they still work at your company, have you tried talking to them about it?

Title: Is this awkward spacing some type of style?

Body:
In reading another programmers code, he uses a format I have never seen.  E.G.

```<code>    namespace MyNs.HereWeAre
         {//tab here for some reason
         public class SomeClass
               {//here's another tab
               public string Method()
                    {//yet another tab
                    string _variable = "";//no tab implementation
                    return _variable;
                    }
               }//eof - class  (Yes these eof comments are on every file)
        }//eof - namespace
// eof - file
</code>```

I'll admit...this code makes me angry.  It is difficult to achieve this style.  One needs to fight the default formatting provided by the IDE, visual studio.

I could swallow this pill a little easier if I knew that there was a good reason for this style.  Does this style stem from some other programming language/IDE?


答:
.NET-only answer

To the best of my knowledge, there's no way you can retrieve the actual value of the parameters passed to a method.

Sure, you can get an array of ParameterInfo objects, through which you can get to know a lot about the parameters... but sadly you can't access their values.
Granted, there are some ways to investigate the stack trace, but they are not guaranteed to be robust enough under all conditions.

So, no, it appears that such a tool can't even be developed for .NET.

I don't know about other platforms, though.


问:
Multi-project multi-team Scrum
2 teams (A and B) in different geo locations are developing Project P.

Both of the teams are also developing few other smaller projects: A has projects PA1 and PA2. B has PB1 and PB2. P is the only one common to the 2 teams.

The Scrum design today:

Each team has a PO, and they decide on the priorities together.

One common Backlog that contains stories from project P and from PA1 and PA2. PB1 and PB2 are done off-scrum.

Each team has its own sprint and SM. Team A picks stories from the backlog that are related to projects P, PA1 and PA2. Team B takes stories only related to P.

The problem:

I want to manage PB1 and PB2 in Scrum as well.

Possible solutions:

Add PB1 and PB2 to the same Backlog? - will complicate the backlog even more than now.

Separate to 3 backlogs (P, PA1-2, PB1-2)? - There is a rule of "one backlog per team"... Should we break it? And is it even supported in TFS?

Any idea how to solve the problem?

答:
I'm currently 2/3rd of the way through Agile Software Requirements: Lean Requirements Practices for Teams, Programs, and the Enterprise and I would highly recommend that book as it covers a lot of the topics issues involved in scaling out agile process to more than one team and maintaining backlogs for enterprise-level products (i.e. those that might span years)

Although I haven't encountered your specific situation so I can't really say how well my advice would work in practice, based on my own experience with Agile, combined with external reading, this is what I would suggest:

Maintain separate backlogs for each product. So you would have five backlogs: P, A1, A2, B1, B2. This way each backlog clearly indicates where you are in that product's development and what lays ahead for that product.

When you have too many stories in a backlog, you reduce overall agility as there's more things for you to manage.  Having 5 different products in one backlog won't be very productive.  Especially if you have more than one product owner.  How much moving around would you have to do if you had a single backlog and all of a sudden your CTO comes to you and says, A2 is your highest priority, put everything else on hold?

Leave product backlog at a somewhat high-level (i.e. don't break stuff down to 1-3pt). Having only larger items will again reduce the number of stories and the teams need to deal with and will make it much easier to prioritize work.

Create 2 team backlogs: A and B. Based on business needs and priorities you should able to pull stories from P, A1, and A2 and transfer those into A.  And P, B1 and B2 would get transferred into B.

Ideally you would only have several iterations worth of stories in the team backlogs. This way as business needs and priorities shift, you'll be able to adjust the volume of stories that you pull from each of the product backlogs.

These team backlogs would take product stories and possibly break them down into finer chunks with more details defined.  But you'd only fill in details when the team is ready to actually do the work.

The positive thing is that having separate product backlogs means that you'll have 5 velocities and you will be able to predict exactly when each feature for those products will be delivered.

The challenge will be to standardize the point scale across the 5 projects and 2 teams because if different products/teams use different point scale, your velocity will be worthless.  The book I mentioned above talks about some of the ways for this standardization.  Basically, you want to start with same base weight (e.g. 1pt ~ 1 day of work).  Also having scrum of scrums meetings (possibly with technical leads) will help with higher level planning, equalizing the point scale and coordination of work between the teams.

Title: Multi-project multi-team Scrum


答:
I personally stick to "about column 80" for my end of line because further than that causes wrapping or lost code when you print it.

There's punch card legacy as well, but I don't think laser printers or 8.5x11 inch paper was set to conform to punch card limitations.


问:
What popular "best practices" are not always best, and why?
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.

答:
Object Relational Mapping... http://en.wikipedia.org/wiki/Object-relational_mapping

I don't want to ever be abstracted away from my data, nor do I want to lose that precise control and optimization.  My experience with these systems has been extremely poor... The queries generated by these abstraction layers is even worse than what I've seen from off-shoring.

ContentLicense: CC BY-SA 2.5


问:
Heavy use of static methods in a Java EE web application?
Generally I am asking if this is a norm. The application architecture includes spring and the zk framework. I personally can't help but think this introduces a number of problems. I mean...this is a lot of non synchronized functionality. On top of that we are using an Apache project that, through my browsing of source, appears to use a singleton which has methods that are not thread safe. Changed in a newer version however we are not free to migrate the library at this time.

My real question is, is there a justifiable reason for using a large quantity of static methods in a JavaEE application? I was an ASP.NET dev before this and never encountered this. Instincts dictate this is bad architecture but I am unfamiliar with the stack. There are other warning signs such as a lack of conventional generic convention use. Is this the norm?

What is foreign in one platform may not be in another.

答:
It's certainly not idiomatic in Java, C# or most any OO language to have a lot of static methods that make assumptions about the state of the universe (typically indicated by use of static variables). I've experienced the pain of untangling at least two large-scale applications and one integration test project that introduced static variables everywhere, including one that only allowed one user to be instantiated at any given moment, because the static User.getUser() method was the only way to get an active instance of the user class. That was very painful.

However, it was bad code. I've seen bad code just like this in C#, in Perl, and in C++. It's a crutch that a certain category of procedural programmers reach for because it feels kind of familiar. Global state is easy to understand, until enough code has been produced that it isn't.

There are a few things for which global state makes sense, but in an idiomatic Java application, these should be confined to not much more than a logging framework (so that you can call something like LogManager.getLogger("somename"), the global dependency bindings map that might be required by a dependency injection framework, and perhaps something that is fairly expensive to build, like an object-relational mapper's session factory.

If you're using Spring sensibly, dependency lookup is typically confined to a narrow part of the application. I've seen Spring used essentially to implement the Service Locator pattern, which essentially has each class constructor ask for its dependencies by calling out to Spring, but this is just asking for pain later and usually frustrates testability, since unit testing shouldn't need to rely on the dependency injection framework. Instead, the locus of Spring usages should be small: I usually have the controller factory in an MVC project build the dependencies needed. For services, there's also usually a reasonable place that you can hook in that's relatively narrow.

Considering that J2EE was sort of an architecture-astronaut version of object purity, I'd almost be more surprised to see lots of static (global) state in a J2EE app. However, knowing that a lot of junior engineers who don't quite know how to do loose coupling sensibly and senior engineers entrenched in procedural ways of solving problems are often thrown at a large-scale project, it's not actually that surprising to see a spaghetti and meatballs approach to a poorly understood problem domain when just the right combination of the wrong people was put on a project.


问:
How to handle different web root running in iis on locahost vs. web server (iis7)
I have several websites that I help manage. When running on my local machine (under iis7), the websites run on under a folder on my machine d:\WebRoot\TheWebsiteName and run as htt://localhost/TheWebsiteName, but when they are deployed they run as http://www.TheWebsiteName.com (also running under iis7)

Currently I am handling the path to the website resources (images, javascript, etc) via code. But I was wondering if there was a better way to handle this rather than writing specialized code in the website.

Thanks!

答:
For each of the websites setup a hostname in C:\Windows\System32\drivers\etc\hosts as a loopback to your local machine:

```<code>127.0.0.1    dev.thewebsitename.com
127.0.0.1    dev.thewebsitename.co.uk
127.0.0.1    dev.anotherwebsitename.com
</code>```

this way you won't have to do any special mapping for your website resources. You can then setup multiple websites in IIS7 as you would do on your live webserver that only serve for the specified urls above. All you then need to do is change your web project's start url to be the new dev address and it will all be working.

I always then setup the different test servers exactly the same so all you need to do is change the subdomain to http://uat.thewebsitename.com etc. If you have a lot of sites you can also created a page with links to all the different sites and then have that bookmarked.

Also if you have a CDN for images you can either add that url as a loopback too, or just upload the images when developing. If you have them locally the speed will be great but you will need to make sure that you remove that loopback when you test.

This always worked like a dream for me and because it replicates your live servers and things like incorrect image/script urls will show up when developing. It does take a little more time to setup but is worthwhile and if you script it using PowerShell it won't be painful if you have to set it up again or for another developer.

Body:
For each of the websites setup a hostname in C:\Windows\System32\drivers\etc\hosts as a loopback to your local machine:

127.0.0.1    dev.thewebsitename.com
127.0.0.1    dev.thewebsitename.co.uk
127.0.0.1    dev.anotherwebsitename.com

this way you won't have to do any special mapping for your website resources. You can then setup multiple websites in IIS7 as you would do on your live webserver that only serve for the specified urls above. All you then need to do is change your web project's start url to be the new dev address and it will all be working.

I always then setup the different test servers exactly the same so all you need to do is change the subdomain to http://uat.thewebsitename.com etc. If you have a lot of sites you can also created a page with links to all the different sites and then have that bookmarked.

Also if you have a CDN for images you can either add that url as a loopback too, or just upload the images when developing. If you have them locally the speed will be great but you will need to make sure that you remove that loopback when you test.

This always worked like a dream for me and because it replicates your live servers and things like incorrect image/script urls will show up when developing. It does take a little more time to setup but is worthwhile and if you script it using PowerShell it won't be painful if you have to set it up again or for another developer.


答:
Presuming the resources are local, you should not need any special code at all -- just use relative paths to your resources and it will work in any environment. IE, use:

```<code><script src = "scripts/whatever.js"></script>
</code>```

Don't use something like:

```<code><script src = "http://mylocalmachinename/scripts/whatever.js"></script>
</code>```

If you are doing some CDN-like thing with a separate images domain then you will need some code somewhere.

Title: How to handle different web root running in iis on locahost vs. web server (iis7)

Body:
I have several websites that I help manage. When running on my local machine (under iis7), the websites run on under a folder on my machine d:\WebRoot\TheWebsiteName and run as htt://localhost/TheWebsiteName, but when they are deployed they run as http://www.TheWebsiteName.com (also running under iis7)

Currently I am handling the path to the website resources (images, javascript, etc) via code. But I was wondering if there was a better way to handle this rather than writing specialized code in the website.

Thanks!

Body:
Presuming the resources are local, you should not need any special code at all -- just use relative paths to your resources and it will work in any environment. IE, use:

<script src = "scripts/whatever.js"></script>

Don't use something like:

<script src = "http://mylocalmachinename/scripts/whatever.js"></script>

If you are doing some CDN-like thing with a separate images domain then you will need some code somewhere.


答: Visual Studio 2008, but not 2010, had a nice addin called HyperAddin for this purpose. Basically you would write #anchor in a comment, and elsewhere use code:#anchor to create a link to that comment. It also supported automatic word wrap in comments, and other little features.</p>


答:
There's no language-agnostic way of dealing with this problem: the solution is very much tied to your method of consumption of this information and what your language and tools can natively support.

If your language and IDE has a way to create and links to code elements (like C# XML Doc Comments or Java Doc), you can associate your documentation with a relevant code element and then link to that element from the other locations which are related to this. This might be good enough as the basis for a knowledge-base to consume through your IDE. You can probably extract this meta-information and build reference documentation that could be easier to consume.

If your IDE doesn't support this sort of linking, or you don't want to consume this information through your IDE, you'll need to go to something external, at which point a Wiki is the easy solution. A hyperlink to an article can be represented in any source file and anything starting http:// is easily followed by any developer.


问:
Abstract Data Type and Data Structure
It's quite difficult for me to understand these terms. I searched on google and read a little on Wikipedia but I'm still not sure. I've determined so far that:

Abstract Data Type is a definition of new type, describes its properties and operations.

Data Structure is an implementation of ADT. Many ADT can be implemented as the same Data Structure.

If I think right, array as ADT means a collection of elements and as Data Structure, how it's stored in a memory. Stack is ADT with push, pop operations, but can we say about stack data structure if I mean I used stack implemented as an array in my algorithm? And why heap isn't ADT? It can be implemented as tree or an array.

答:
Simply put, an ADT (Abstract Data Type) is more of a logical description, while a Data Structure is concrete.

Think of an ADT as a picture of the data and the operations to manipulate and change it.

A Data Structure is the the real, concrete thing. It can be implemented and used within an algorithm.

Title: Abstract Data Type and Data Structure


问:
Is it true that first versions of C compilers ran for dozens of minutes and required swapping floppy disks between stages?
Inspired by this question.

I heard that some very very early versions of C compilers for personal computers (I guess it's around 1980) resided on two or three floppy disks and so in order to compile a program one had to first insert the disk with "first pass", run the "first pass", then change to the disk with "second pass", run that, then do the same for the "third pass". Each pass ran for dozens of minutes so the developer lost lots of time in case of even a typo.

How realistic is that claim? What were actual figures and details?

答: I had to do the floppy dance on my old 128K Mac for various applications, so I don't doubt this for a minute, although I couldn't give any details.  I wouldn't be surprised if that's not part of why BASIC interpreters were so ubiquitous on early personal computers (no need for multiple passes, symbol tables, etc.).  </p>


问:
Using version control to manage site backups?
Last week I started making daily backups of my relatively small (~300mb) site. The backups are zipped, so it's less space, but it will quickly add up, especially as my site gets bigger.

I was thinking of unzipping the latest backup, and from now on just using mercurial to add/update files from newer backups.

Are there any drawbacks to this? Is there a better way to do it?

答:
IMO this is the best way, I'm doing it like this as well.

(just commit every change and push the whole thing to a private repository on Bitbucket)

It makes absolutely no sense to always copy the whole 300 MB if only a few files have changed.

Plus, you get a changelog "for free" (which you don't have if you just make a ZIP file every day).


问:
Why is 24 lines a common default terminal height?
80x24 characters seems to be a very common default for terminal windows.  This answer provides a very good historical reason as to why the width is 80 characters.

But why is the height commonly 24 (or 25) lines?

答:
The height of the vt100 terminal.

Emulators get the best vt100 compatability at that size.


答: Definitely the way to go here. One additional plus -- you can easily revert changes in many cases if need be. Saved me from more than a few bad updates . . .</p>

Title: Using version control to manage site backups?

Body:
Last week I started making daily backups of my relatively small (~300mb) site. The backups are zipped, so it's less space, but it will quickly add up, especially as my site gets bigger.

I was thinking of unzipping the latest backup, and from now on just using mercurial to add/update files from newer backups.

Are there any drawbacks to this? Is there a better way to do it?


问:
How can I move from Java and ColdFusion to Ruby on Rails?
Currently I work with ColdFusion 9+ and some Java in a Windows environment. Prior to ColdFusion, my background was in Java and JSP.

I'm considering a move towards Ruby on Rails, as I think it would be a real challenge, keep things fresh, and provide more job opportunities.

In order to get into it, I started to build my personal website in Rails 3.0. But what else can I do to make this transition from what I know now to Ruby and Rails? Are there specific or idiomatic aspects of Ruby or Rails I should keep in mind when switching over from a ColdFusion and Java mindset?

答: For anybody else considering this, I also recommend learning and working with a framework while still working in CF.  CFWheels is the most similar to Rails, and you'd be able to transfer over the concepts pretty easily.  But I'd recommend to any CF developer who hasn't done work in a framework to try it.  It forces you to think in very different ways.</p>


问:
Are comments considered a form of documentation?
When I am writing small scripts for myself, I stack my code high with comments (sometimes I comment more than I code). A lot of people I talk to say that I should be documenting these scripts, even though they are personal, so that if I ever do sell them, I would be ready. But aren't comments a form of documentation?

Wouldn't this:

```<code>$foo = "bar"; # this is a comment
print $foo; # this prints "bar"
</code>```

be considered documentation, especially if a developer is using my code? Or is documentation considered to be outside of the code itself?

答:
Comments are a form of documentation.  An inferior form, and one that suggests you have located an area of your code that can be better factored.

It sounds like you comment things compulsively.  Having other options may be a good thing.  I can think of three superior forms of documentation:

1) Factor your code better.  Instead of adding in a comment, extract a method or function whose name is the text of the comment you were about to write.  So the code says what your comment was about to say.

2) Tests.  This is the form of documentation I usually search out.  Unit tests and acceptance tests are living documentation, and can read easily if lots of meaningful methods are used to express intent, as in point 1.

3) For scripts, the --help option. This is where you can go nuts on doc.  Stick in examples, anticipate what the user would need.

In summary, if you find yourself inclined to stick in a comment, check if there is a way to communicate to the reader by structuring the code better.  Or is there a test that communicates why that code is there?  If you still feel inclined to comment it, admit defeat, and do it.


答:
I use git for this purpose.  Assuming unix/linux:

```<code>cd /path/to/site
git init
chmod 600 .git
vi .gitignore  # add any tmp files you dont want here
git add .
git commit -m "initial commit"
</code>```

Then, add this to the nightly crontab:

```<code>0 3 * * *     cd /path/to/project; git add . && git add -u && git commit -m "Daily Commit"
</code>```

You could also setup a push to a remote (like github) for true backups.

Body:
I use git for this purpose.  Assuming unix/linux:

cd /path/to/site
git init
chmod 600 .git
vi .gitignore  # add any tmp files you dont want here
git add .
git commit -m "initial commit"

Then, add this to the nightly crontab:

0 3 * * *     cd /path/to/project; git add . && git add -u && git commit -m "Daily Commit"

You could also setup a push to a remote (like github) for true backups.


答:
Git is your best choice, since it allows "cheap" commits, branches, etc. every commit is simply a diff of the previous commit, so the size is minimal, for example if you have

```<code>index.html
image.png
README.txt
Makefile
main.c
</code>```

and you only change index.html, then that is all that is stored in the commit, making git extremely space efficient, whats more, it only stores the one or two lines you changed, it could be 500000 line html file (WoAH) making it super fast.

This does mean that the first push to whatever git server that you're using might be long. But everything after that should take no time at all.

And the beautiful thing is, everything can be done locally, you can do as many changes as you want to a local repository, commit as many times as you want, and then push all at once, and since repositories can be local, you can push to just another physical (in the virtual sense :P) on your hard drive, or to a webserver, or through email even!

Body:
Git is your best choice, since it allows "cheap" commits, branches, etc. every commit is simply a diff of the previous commit, so the size is minimal, for example if you have

index.html
image.png
README.txt
Makefile
main.c

and you only change index.html, then that is all that is stored in the commit, making git extremely space efficient, whats more, it only stores the one or two lines you changed, it could be 500000 line html file (WoAH) making it super fast.

This does mean that the first push to whatever git server that you're using might be long. But everything after that should take no time at all.

And the beautiful thing is, everything can be done locally, you can do as many changes as you want to a local repository, commit as many times as you want, and then push all at once, and since repositories can be local, you can push to just another physical (in the virtual sense :P) on your hard drive, or to a webserver, or through email even!


问:
Design a program and methods of doing so
I'm working on becoming a self-taught  programmer. I've read a little bit through a lot of languages and I decided to start with Java and have been using it for several months now. I didn't have much of a problem since most my programs are relatively simple, or games that don't take much planing. That is until my last project I challenged myself with, making a client/server chat applications with a GUI. With only the idea in my head on how sockets worked and my newly learned syntax I started at it. Before I knew it I ended up with a jumbled mess of program that I was finding VERY difficult to work with and eventually I was just so ridiculous I couldn't get simple things to work and I had to delete everything and now I'm starting over. So I took it that I need some better practices.

Now for the questions. As someone who is self-taught I'm bound to develop several bad habits, and I do virtually zero planing before writing a program aside from the idea in my head, so:

What are some good ways I might start developing better programming habits?

When planning a program, are there any good methods of doing so?

Besides experience, what else is it that I might need before trying to actually take on a big real-world project as a programmer? Like one for a job. (How many languages should I know, what kind of problems should I be able to handle, that kind of thing. )

答:
Program more, go back and look at your old code and try to understand what its doing and how its doing it, and program more.

There are hundreds may thousands of different ideas on how to develop software wikipedia has a good list. Agile and TDD are the most current buzz, but by no means the best.

More experience :) You might want to start with something small and then just add more and more features to that project, like make a website, add the ability to login as different users, add a way to send messages or a real time chat, add a small game, etc. What you need to know depends on the job you want, there are plenty of questions here that give more detail if you look by type.


答:
Early terminals were built around the same cathode ray tubes that were used for televisions. In the 1960's and 1970's these were all 4:3 aspect ratio.

If the display needs to fit 80 characters across the width then given the aspect ratio of the standard characters which was taller than 3:4 (if I remember correctly) and allowing for a larger space between lines than between characters you get to fit 24 or 25 lines on the display.

I haven't done the exact maths because I can't remember (or find) the exact character aspect ratio or line spacing.

Title: Why is 24 lines a common default terminal height?

Body:
80x24 characters seems to be a very common default for terminal windows.  This answer provides a very good historical reason as to why the width is 80 characters.

But why is the height commonly 24 (or 25) lines?


问:
Can Software Engineers become certified Professional Engineers (PE)?
Does anyone know if a Software Engineer can become a certified Professional Engineer or PE for short?  I know that my buddies who are Mechanical, Electrical, or Civil Engineers were able to become PEs by taking an exam.  Does such an exam exist in Software Engineering?</p>

答:
In April 2013, the Professional Engineer exam for Software Engineering was offered for the first time. The IEEE Computer Society, IEEE-USA, and National Council of Examiners for Engineering and Surveying (NCEES) partnered to develop an exam specifically for software engineers. State boards issue the exams and manage the requirements for taking and passing the exam.

However, the last time this exam will be offered will be in April 2019. In the news release, the NCEES cited a low candidate population. The examination was offered 5 times and only 81 candidates sat for the exam.

ContentLicense: CC BY-SA 4.0


答: One word of advice on story points---I generally do not like to share the raw points with outside parties. Team A and Team B (especially if they are not co-located and in conversation with one another) are going to have their own relative points and should be allowed to gauge their own baseline and level of effort for each user story. I've seen far too many discussions between stakeholders and the product owner over why team A is able to have a velocity of 50 per sprint while team B has a velocity of 25. I'm all for transparency, but you have to protect your team members from that kind of discussion. If you have to report anything externally, I'd come up with a translated tee-shirt size from the points like "1-3 (Small) 5-13 (Medium) 20-40(Large) 100+(XL)." This is especially important when you have strong, opinionated stakeholders who are not familiar with Scrum and the idea of story points and relative estimation. Your best bet is to just to let them see the backlog's priorities, the general release plan, and maybe a backlog burn-down chart that shows no points, only the trend line with dates. Those points are there first and foremost to elicit discussion among the team members about the level of effort. After that takes place, it may help you as a product owner or scrum master to plan better. It was never meant to be an objective score for your stakeholders to judge your teams efficacy or hard work. Making it so will discourage them from being honest.</p>

Title: Multi-project multi-team Scrum

Body:
2 teams (A and B) in different geo locations are developing Project P.

Both of the teams are also developing few other smaller projects: A has projects PA1 and PA2. B has PB1 and PB2. P is the only one common to the 2 teams.

The Scrum design today:

Each team has a PO, and they decide on the priorities together.

One common Backlog that contains stories from project P and from PA1 and PA2. PB1 and PB2 are done off-scrum.

Each team has its own sprint and SM. Team A picks stories from the backlog that are related to projects P, PA1 and PA2. Team B takes stories only related to P.

The problem:

I want to manage PB1 and PB2 in Scrum as well.

Possible solutions:

Add PB1 and PB2 to the same Backlog? - will complicate the backlog even more than now.

Separate to 3 backlogs (P, PA1-2, PB1-2)? - There is a rule of "one backlog per team"... Should we break it? And is it even supported in TFS?

Any idea how to solve the problem?


问:
If you were the manager of a team of 25 developers, how would you motivate them?
Imagine yourself hired by a new startup backed with few millions coming from venture capitalists.

Your mission: organize the development of the next killer app.

25 developers is too much to take care of each individually, so what decision(s) you would make to motivate them?

I will appreciate any answers from stock options to free cookies ;)

Of course the trick here (unless you are really a manager of a such startup), is put yourself in the shoes of one of those programmers.

EDIT: it's an imaginary context. The purpose of this story is to stimulate your wishes. I want to capture what motivates developers.

答:
Team Events might help.
Events like going to a sports game and so forth might motivate part of the group.
I guess the balance is finding out an event that will include everyone.</p>


问:
Best way to set sys.path for "hot library" development in Python?
I have my Python source structured as follows:

```<code>+-branchname/
  +-dst/
  +-src/
  | +-library/
  | | +-cleese/
  | | | +-test/
  | | | | +-__init__.py
  | | | | +-test_cleese.py
  | | | +-__init__.py
  | | | +-cleese.py
  | | +-palin/
  | |   +-test/
  | |   | +-__init__.py
  | |   | +-test_palin.py
  | |   +-__init__.py
  | |   +-palin.py
  | +-productline/
  |    +-circus/
  |    | +-test/
  |    | | +-__init__.py
  |    | | +-test_circus.py
  |    | +-__init__.py
  |    | +-circus.py
  |    +-grail/
  |      +-test/
  |      | +-__init__.py
  |      | +-test_grail.py
  |      +-__init__.py
  |      +-grail.py
  +-branch_root_marker
</code>```

Entry points are in circus/ and grail/, as well as (possibly) each of the test/ directories, depending on how testing is implemented.

I have multiple copies of this source tree present on local storage at any one point in time (corresponding to various maintenance and feature branches), so I cannot set PYTHONPATH in my shell without some pain. (I would need to remember to change it each time I switched to work on a different branch, and I am very forgetful)

Instead, I have some logic that walks up the file tree, starting at the "current" file location, moving from leaf towards root, looking for branch_root_marker. Once the root directory of the current working copy is found, it adds library/ and productline/ to sys.path. I call this function from each entry-point in the system.

```<code>"""Add working copy (branch) to sys.path"""

import os
import sys

def _setpath():
    """Add working copy (branch) to sys.path"""

    markerfile = "branch_root_marker"
    path = ""
    if ("__file__" in locals() or globals()) and __file__ != "__main__":
        path = __file__
    elif sys.argv and sys.argv[0] and not sys.argv[0] == "-c":
        path = sys.argv[0]
    path = os.path.realpath(os.path.expandvars(path))
    while os.path.exists(path):
        if os.path.exists(os.path.join(path, markerfile)):
            break
        else:
            path = os.path.dirname(path)
        errormsg = " ".join(("Could not find", markerfile))
        assert os.path.exists(path) and path != os.path.dirname(path), errormsg

    path = os.path.join(path, "src")
    (_, subdir_list, _) = os.walk(path).next()
    for subdir in subdir_list:
        if subdir.startswith("."):
            continue
        subdir_path = os.path.join(path, subdir)
        if subdir_path in sys.path:
            continue
        sys.path.append(subdir_path)
_setpath()
</code>```

Currently, I need to keep a separate but identical copy of this function in each entry point. Even though it is quite a short function, I am quite distressed by how fragrantly the DRY principle is being violated by this approach, and would love to find a way to keep the sys.path modification logic in one place. Any ideas?

Note:- One thing that springs to mind is to install the sys.path modifying logic into a common location that is always on PYTHONPATH. Whilst this is not a terrible idea, it means introducing an installation step that needs to be carried out each time I move to a fresh environment; another thing to remember (or, more likely, forget), so I would like to avoid this if at all possible.

答:
OK, I started to craft a solution that involved PEP 302 import hooks.  Way too complicated.

I think you answered your own question with:

this "gateway" script could implement all manner of bootstrapping functionality - for example, ensuring that virtualenv is set up correctly and activated for the current branch.

if you are already using virtualenv, put the logic you have in the "~/venv/or-whatever-path/bin/activate" script that is already there.  I'd suggest listing of possible entry points and prompting for a response (list with numbers and a raw_input() statement will do) if you are not specifying one.

I'd also put the name of your branch in to $PS1 so that is shows up in the tab name or window title of your terminal. I so something similar and change the color of the prompt so I don't do the right thing in the wrong place.


问:
Should a class without instance variables be considered a class?
Say you need to implement a few closely related functions that provide a piece of functionality, but there is no need to track any state between those functions, they just sometimes pass some parameters between themselves. What would be the best decision from the design standpoint? Make it a class, or just a separate source file that contains these functions?

UPD: Objective-C, no namespaces

答: You can group those functions into utility classes. Math in Java is a good example of this. It has no state and just lets you make static calls to do things. Putting these related methods in a class makes it clear that they are, in fact, related. </p>


答:
Well it's definitely a class, but I generally wouldn't refer to it as a 'class' in the OO sense of things as they're usually used in different ways.

For instance, in languages that lack free functions like Java, this is the workaround to provide them.

In C++ this is commonly used for function objects.

In your case it seems like a class provides no advantages and so you're better off having them be free functions possibly in a namespace.

Title: Should a class without instance variables be considered a class?

Body:
Say you need to implement a few closely related functions that provide a piece of functionality, but there is no need to track any state between those functions, they just sometimes pass some parameters between themselves. What would be the best decision from the design standpoint? Make it a class, or just a separate source file that contains these functions?

UPD: Objective-C, no namespaces


答:
Sure!  Encapsulating data is certainly not the most important thing about OO!

```<code>struct thingy;

void fun(thingy & t) { t.do_stuff(); }

struct thingy {
   virtual ~thingy() {}
   virtual void do_stuff() = 0;
}

struct thingy_d1 : thingy {
  void do_stuff() { std::cout << "Doing stuff.\n"; }
};
struct thingy_d2 : thingy {
  void do_stuff() { std::cout << "Doing other stuff.\n"; }
};
</code>```

The Command Pattern very often takes this form.

Body:
Sure!  Encapsulating data is certainly not the most important thing about OO!

struct thingy;

void fun(thingy & t) { t.do_stuff(); }

struct thingy {
   virtual ~thingy() {}
   virtual void do_stuff() = 0;
}

struct thingy_d1 : thingy {
  void do_stuff() { std::cout << "Doing stuff.\n"; }
};
struct thingy_d2 : thingy {
  void do_stuff() { std::cout << "Doing other stuff.\n"; }
};

The Command Pattern very often takes this form.


答: A class defines how objects are created.  If the object does not require an internal state, the class won't have any instance variables.  There are lots of reasons why this might be useful--things like objects implementing the Strategy pattern spring to mind. </p>


答: If you're in a language that requires that all functions be part of a class (Java, C#, etc,) you don't have much of a choice but to make them part of a class.  Otherwise, just put them in their own file with its own namespace. That keeps things simpler.</p>


答:
"Unit Test Everything."

I've heard it said often that all code should have unit tests, a point I disagree with.  When you have a test for a method, any change to the output or structure of that method must be made twice (once in the code, once in the test).

As such, unit tests should be, in my opinion, proportional to the structural stability of the code.  If I'm writing a layered system from the bottom up, my data access layer will have tests out the wazoo; my business logic layer will be pretty well tested, my presentation layer will have some tests, and my views will have little to no testing.

Title: What popular "best practices" are not always best, and why?

Body:
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.


答: No. That's a namespace. Calling it a class is just silly. Why would you pointlessly wrangle one feature into becoming ... a feature that the language already provides as first class?


答:
There is a major difference that seems to be forgotten about classes vs namespace.

Classes can be extended, where as namespaces can't. Even in the scenario that you describe, it is unlikely that it can be totally ruled out that in future there won't be a reason to extend your group of functions to provide a slightly altered group of functions. And in that scenario the instantiation of the class has a property, which is the type of class.

In some languages where static methods cannot be overloaded in inheriting classes, a class with only static methods could be considered as nothing more than a namespace.


问:
Efficient ways to model cars moving along a road
This has never come up, so I've never thought how a data or programming model should work that simulates (a) bird's eye view of cars moving and some rudimentary physics, (b) how the cars would follow a road layout and (c) how an efficient data structure for roads would look like.

Obviously, this question also means to ask how the road data structures would interact with cars.

Any recommendations, or reviews of such data models?

答:
Roads need defined lanes:  a spline that determines the center of each lane is probably the most convenient.  Lane and shoulder boundaries may also make sense, if only for road-drawing purposes.

The interesting datastructure element is the ability to split and merge lanes:  your lane splines should be associated with edges in a directed multigraph.

Cars need a position and a velocity; they should be able to efficiently query which cars are ahead/behind/beside them, in order to do rudimentary navigation.  They will also need a bounding box, and of course a collision model...


问:
What is the difference between Agile Modeling and the Agile Manifesto?
By searching for the different software development methods I found that there are two AM:

Agile Modeling

Agile Manifesto

The problem is that I can't get the difference between them. If one is a part of another? or an update to the other?

答:
Agile Modeling is:

Agile Modeling (AM) is a practice-based methodology for effective modeling and documentation of software-based systems.  Simply put, Agile Modeling (AM) is a collection of values, principles, and practices for modeling software that can be applied on a software development project in an effective and light-weight manner.  The secret to AM isn’t the modeling techniques themselves -- such as use case models, class models, data models, or user interface models -- but how they’re applied. You may take an agile modeling approach to requirements, analysis, architecture, and design.

While the Agile Manifesto is:

The Agile Manifesto was written in February of 2001, at a summit of seventeen independent-minded practitioners of several programming methodologies. The participants didn't agree about much, but they found consensus around four main values.

The four main values being:

Individuals and interactions over processes and tools

Working software over comprehensive documentation

Customer collaboration over contract negotiation

Responding to change over following a plan

Agile software development is a group of similar methodologies, some of the more popular ones are:

Agile Modeling

Agile Unified Process (AUP)

Crystal Clear

Dynamic Systems Development Method (DSDM)

Essential Unified Process (EssUP)

Exia Process (ExP)

Extreme Programming (XP)

Feature Driven Development (FDD)

Kanban (development)

Open Unified Process (OpenUP)

Scrum

Velocity tracking

To summarize:

Agile Modeling is one of the various agile methodologies,

The Agile Manifesto is the document that introduced the term "agile" and the core values of agile software development.


答:
JavaBeans

The use of JavaBeans in Java. See my question Why shouldn't I use immutable POJOs instead of JavaBeans? on StackOverflow.


问:
Are nested loops always O(n^k)?
If I have a loop within another loop, yet I know the inner loop will only run once, will this algorithm still be O(n^2)?

```<code>For i = 1 to n do

     For j = 1 to i do

          If (i==j) do

              For k = 1 to n

                  {Do stuff}
</code>```

The very inner loop will run at most 1 time, since i will only equal j once per iteration of the second loop. Is this still n^3?

答:
Think of it this way. Regardless of N, the innermost function will only ever execute once per execution of the second loop. This is to say, the amount of times it executes does depends on N linearly. This means that you can treat everything inside the first loop as a linear (O(n)) time operation (assuming {do stuff} is also constant time). If you consider the outermost loop, you see that you do something that takes O(n), n times. This means the overall runtime is O(n^2)

If you double N, there will be a total of N^2 extra iterations. Thus, the overall runtime is N^2.

Title: Are nested loops always O(n^k)?


答: No, nested loops do not automatically mean your algorithm is O(n^k).  The basic unit of work in your example is {Do stuff}, so you need to count how many times that will execute as n increases.  You don't even need the j loop, since it only counts up from 1 to i and does nothing until it reaches i.  Only on that one iteration does it actually do any work, so your example code is O(n^2).

Title: Are nested loops always O(n^k)?

Body:
If I have a loop within another loop, yet I know the inner loop will only run once, will this algorithm still be O(n^2)?

```<code>For i = 1 to n do

     For j = 1 to i do

          If (i==j) do

              For k = 1 to n

                  {Do stuff}
</code>```

The very inner loop will run at most 1 time, since i will only equal j once per iteration of the second loop. Is this still n^3?


问:
Is the 14th line of The Zen of Python a reference to Dijkstra?
Python's Zen states on line 14 that:

Although that way may not be obvious at first unless you're Dutch.

Is this a reference to the famous Dutch computer scientist Edsger W. Dijkstra?

答:
I'm pretty sure it's a reference to Guido van Rossum.

He's the creator and BDFL of Python.


答:
Although that way may not be obvious at first unless you're Dutch.

refers to the previous line:

There should be one-- and preferably only one --obvious way to do it.

And it has been argued that it's in reference to Dijkstra's thoughts on language design as expressed in his comments for the GREEN language (an early ADA):

I thought that it was a firm principle of language design --out of concern for programming as a human activity-- that in all respects equivalent programs should have few possibilities for different representations (possibility for differences ideally not going beyond the arbitrary choice of identifiers and the arbitrary ordering of syntactically unordered components). Otherwise completely different styles of programming arise unnecessarily, thereby hampering maintainability, readability and what have you. This requires from the language designers the courage to make up their minds! The designers of the GREEN language have repeatedly lacked that courage, and have provided multiple ways of doing the same thing.

The quote has been used to point the antithesis between Python's design (There’s only one way to do it) to Perl's (There's more than one way to do it)

Slogans, semi-official and unofficial:

Perl: "There's more than one way to do it."

"There's more ways to do it than you can remember, probably more than you can even recognize."

Python: "There should be one -- and preferably only one -- obvious way to do it."

At least we tried to pick the right way.
  (I have seen a progenitor of this remark attributed to Dijkstra: "I thought..." - Edsger W. Dijkstra on GREEN, an early version of Ada)

Further digging revealed this old thread on a Python mailing list, appropriately named "Dijkstra on Python". The thread is centered around the same quote, and the philosophical differences between Python and Perl.

But, the Dutch is indeed Guido van Rossum, as Tim Peters (author of the Zen of Python) reveals:

In context, "Dutch" means a person from the Netherlands, or one imbued with
  Dutch culture (begging forgiveness for that abuse of the word). I would
  have said French, except that every French person I asked "how do you make a
  shallow copy of a list?" failed to answer

alist[:]

so I guess that's not obvious to them. It must be obvious to the Dutch,
  though, since it's obvious to Guido van Rossum (Python's creator, who is
  Dutch), and a persistent rumor maintains that everyone who posts to
  comp.lang.python is in fact also Dutch. The French people I asked about
  copying a list weren't Python users, which is even more proof (as if it
  needed more).

Or, in other words, "obvious" is in part a learned, cultural judgment.
  There's really nothing universally obvious about any computer language,
  deluded proponents notwithstanding. Nevertheless, most of Python is obvious
  to the Dutch. Others sometimes have to work a bit at learning the one
  obvious way in Python, just as they have to work a bit at learning to
  appreciate tulips, and Woody Woodpecker impersonations.

Title: Is the 14th line of The Zen of Python a reference to Dijkstra?

Body:
Python's Zen states on line 14 that:

Although that way may not be obvious at first unless you're Dutch.

Is this a reference to the famous Dutch computer scientist Edsger W. Dijkstra?


问:
Peter Norvig's paper cited by Brendan Eich
I'm reading Coders at Work and Brendan Eich cites a paper by Norvig, from when he was at Harlequin, "about how design patterns are really just flaws in your programming language."

Can anyone provide the link to this paper?

答:
I think the "paper" is actually the Design Patterns in Dynamic Languages presentation, also cited in Wikipedia for this particular claim:

The design patterns may just be a sign of some missing features of a given programming language (Java or C++ for instance). Peter Norvig demonstrates that 16 out of the 23 patterns in the Design Patterns book (which is primarily focused on C++) are simplified or eliminated (via direct language support) in Lisp or Dylan.

In similar manner, Paul Graham describes design patterns as "the human compiler at work" in Revenge of the Nerds:

This practice is not only common, but institutionalized. For example, in the OO world you hear a good deal about "patterns". I wonder if these patterns are not sometimes evidence of case (c), the human compiler, at work. When I see patterns in my programs, I consider it a sign of trouble. The shape of a program should reflect only the problem it needs to solve. Any other regularity in the code is a sign, to me at least, that I'm using abstractions that aren't powerful enough - often that I'm generating by hand the expansions of some macro that I need to write.

Both quotes are the basis of the Are Design Patterns Missing Language Features discussion on Ward's Wiki.


问:
What popular "best practices" are not always best, and why?
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.

答:
For SQL

Don't use triggers

Always hide tables behind views

In order:

They are a feature that has it's place. You have multiple update paths to a table, or require 100% auditing?

Just why? I would if I was refactoring to maintain a contract, but not when I've read that folk change the view to match any table changes

Edit:

Number 3: Avoiding * with EXISTS. Try 1/0. It works. The column list isn't evaluated as per SQL standard. Page 191


问:
What exactly comprises 'Documentation'?
When we say 'documentation' for a software product, what does that include and what shouldn't that include?

For example, a recent question asked if comments are considered documentation?

But there are many other areas that this is a valid question for as well, some more obvious than others:

Manuals (obviously)

Release notes?

Tutorials

Comments

Any others?

Where is the line drawn. For example, if 'tutorial' is documentation, is 'video tutorial' documentation, or is it something else?

Generally, something in software isn't 'done' until it is implemented, tested and documented. Hence this question, what things should we consider as part of documention to consider something 'done'.

Question inspire from recent customer feedback at our conference indicating that our doc needed more 'samples', which we previously hadn't been as good at considering as we should have been.

Audience: Software developers using our database(s), programming languages and associated tooling (such as admin clients to said DB)

答:
I think you took away the wrong part from your conversation at a conference. Modern software development methodologies advocate that the development team should be working closely with its customers (or a product owner who's acting as a customer proxy). For all work delivered, definition of "done" is something that is negotiated between the team and its customer and is done on recurring basis as the software is being developed.

The problem you ran into is that you had a disconnect between what you assumed the customer needed and what they expected you to deliver so at the end you got the "hey where are all the samples" surprise.

As far as, what is documentation... well, it's pretty much everything you listed and maybe few more things that you didn't. But nobody can tell you how much documentation your project needs. Every project is different and it is up to your team, your product owner and your customers to determine the level and type of documentation that is required for your project.

Some factors that would come into play:

Are you developing software v1.0 and them moving on to other projects or is this on-going, long term project?  Comments/design docs become much more important in the latter case. On the other hand if your customer is a mom-and-pop donut shop and you are writing a website for them that you will never see... well I guess code documentation is nice but not that important.

Are you developing an mobile game or software that is controlling heart rate monitor in a hospital. Guess which one will have definition of "done" that has much more documentation?

Are your customers typical end-users or are they other developers? Do you have an API/SDK that you are exposing?

What is the level of expertise of your customers?  This affects the choice of video tutorial vs. written material vs. some kind of interactive tutorial app

Do your customers care about what changed from version to version. Some do. Most don't. For few it's the law (or close to that) to care.

Title: What exactly comprises 'Documentation'?


问:
How to render a terrain using height maps and getting basic collision detection on top of the terrain and camera (moving on the terrain)
I have loaded a .RAW file into a 2x2 array in my class. The way I am rendering it works fine but I am struggling to get the camera to move on top of the terrain. The terrain renders from 0,0,0 (x,y,z) as that is where I put my camera. My camera class allows to the "camera" to move through the scene. </p>

<p>I want to be able to "walk" on top of the terrain with some basic collision detection (if possible).
Any tips on where to go for this or any tips? </p>

答: If one assumes that (0, 1, 0) is the vector that poins to the sky, a collision occurs, when the terrains height at the cameras X and Z coordinates is greater or equal to the Y coordinate of the camera. The next thing is, the camera needs gravity to stick at the ground.</p>


答:
As Ryathal already mentioned, practice and never stop practicing. Some of the best experience that teaches you skills and redefines how you approach software development are failures. Spectacular failures burn those lessons into your skull.

In addition to straight practice, few more things you could be doing:

Keep reading books. And not just on programming languages themselves, but also on other aspects of software development. Uncle Bob (Robert C. Martin) has a couple which are very worth reading: "Clean Code", "Agile Practices, Patterns and Principles".  Also Pragmatic Programmer is a very highly recommended read.

Surround yourself with people who are better than you at programming. Finding someone who can review your code and who you can bounce ideas of would be very helpful for you. Use this site, as well as SO and CodeReview stackexchange as much as you can, but local person would obviously be better.  TIP: Free food (and beer) goes a long way with many programmers if you are looking for their help/advice.  If you don't have any friends or friends of friends, you could try checking out some local user groups for specific technologies in your area.

Btw, I'm a huge proponent of TDD and one of the key people who is trying to promote its wider adoption at where I work. However, I've seen much more experienced, professional programmers fail miserably while doing what they thought was TDD. I think until you have more experience in software design, TDD will only triple or quadruple the amount of code you need to maintain, and all that code will morph into a nightmare that will make you hate the project you are working on. For now just focus on software itself. Don't worry if it's not automagically testable, most of it will probably end up being throw-away in any case.

Title: Design a program and methods of doing so

Body:
I'm working on becoming a self-taught  programmer. I've read a little bit through a lot of languages and I decided to start with Java and have been using it for several months now. I didn't have much of a problem since most my programs are relatively simple, or games that don't take much planing. That is until my last project I challenged myself with, making a client/server chat applications with a GUI. With only the idea in my head on how sockets worked and my newly learned syntax I started at it. Before I knew it I ended up with a jumbled mess of program that I was finding VERY difficult to work with and eventually I was just so ridiculous I couldn't get simple things to work and I had to delete everything and now I'm starting over. So I took it that I need some better practices.

Now for the questions. As someone who is self-taught I'm bound to develop several bad habits, and I do virtually zero planing before writing a program aside from the idea in my head, so:

What are some good ways I might start developing better programming habits?

When planning a program, are there any good methods of doing so?

Besides experience, what else is it that I might need before trying to actually take on a big real-world project as a programmer? Like one for a job. (How many languages should I know, what kind of problems should I be able to handle, that kind of thing. )