答:
I've come at this from a slightly different direction (and I use mercurial, but philosophically its the same). This isn't my idea, I just use it and it works for my personal stuff.

I created a clone of my repositories in a SkyDrive folder (it could equally be dropbox or another magic sync tool of your choice), I have then configured the instances on my two machines to automatically push to the SkyDrive repository on commit.

When I switch boxes its then just a matter of doing a pull and an update - in theory you'll always be working in a linear fashion even though its in multiple repositories.

The key here is that the SkyDrive repo exists mostly to provide a means to ensure that I've got access to more or less the latest version of the code on both my machines - though it would work as well for more - and to provide an extra backup. Anything that is "done" gets pushed to Kiln (if I were using git and I correctly understand the way the game is played then that would be point at which I do a rebase).

What I really wouldn't want to do is run off a shared folder... if you're using a DVCS then you may as well enjoy the benefit.

Title: Working with Git on multiple machines


问:
Why a static main method in Java and C#, rather than a constructor?
I’m Looking for a definitive answer from a primary or secondary source for why (notably) Java and C# decided to have a static method as their entry point, rather than representing an application instance by an instance of an Application class (with the entry point being an appropriate constructor).

Background and details of my prior research

This has been asked before. Unfortunately, the existing answers are merely begging the question. In particular, the following answers don’t satisfy me, as I deem them incorrect:

There would be ambiguity if the constructor were overloaded. – In fact, C# (as well as C and C++) allows different signatures for Main so the same potential ambiguity exists, and is dealt with.

A static method means no objects can be instantiated before so order of initialisation is clear. – This is just factually wrong, some objects are instantiated before (e.g. in a static constructor).

So they can be invoked by the runtime without having to instantiate a parent object. – This is no answer at all.

Just to justify further why I think this is a valid and interesting question:

Many frameworks do use classes to represent applications, and constructors as entry points. For instance, the VB.NET application framework uses a dedicated main dialog (and its constructor) as the entry point1.

Neither Java nor C# technically need a main method. Well, C# needs one to compile, but Java not even that. And in neither case is it needed for execution. So this doesn’t appear to be a technical restriction. And, as I mentioned in the first paragraph, for a mere convention it seems oddly unfitting with the general design principle of Java and C#.

To be clear, there isn’t a specific disadvantage to having a static main method, it’s just distinctly odd, which made me wonder if there was some technical rationale behind it.

I’m interested in a definitive answer from a primary or secondary source, not mere speculations.

1 Although there is a callback (Startup) which may intercept this.

答:
You've got to start somewhere.  A static main is the simplest execution environment you can have -- no instance of anything (outside of the JVM and the simple string parameters) needs to be created -- so it can "come up" with a minimum of fuss (and low likelihood of a coding error preventing startup, etc) and can do simple things without a lot of other setup.

Basically an application of KISS.

[And, of course, the main reason is: Why not?]

OwnerDisplayName: Konrad Rudolph

ContentLicense: CC BY-SA 3.0


问:
How can I maintain proficiency in multiple languages?
How can I maintain proficiency (if not expertise) in multiple languages?

In any large organization it seems necessary to know more than one language.  For example, this week I've looked at if not written code in the following languages.

VBA

C

C#

Java

Thankfully they're all imperative languages, or I would have lost my mind.

I struggled for a day or so with the C as it's been a while (read: years) since I've used it seriously.

What tips, habits, and training is there for keeping up your knowledge in so many languages?

答:
In our large organisation we have C#+T-SQL or Java+PL/SQL or Java/C++ according to the team.

I'm quite surprised you have to use so many in one place professionally. Some of the c# guys I know tinker with, say, IronPython in their own time for interests sake, but this is hobbyism.

Sorry to say, but "Jack of all trades, master of none" would be my sentiment,

I can imagine in a small shop you're exposed to much more, but a large shop would have dedicated teams.

ContentLicense: CC BY-SA 2.5


答:
That just feels vaguely abusive to me.  A constructor is used for the initialization of an object: it sets up an object, which is then used by the code that created it.

If you put basic usage functionality inside of the constructor, and then never actually use the object that the constructor creates in external code, then you're violating the principles of OOP.  Basically, doing something really weird for no apparent reason.

Why would you want to do that anyway?

Title: Why a static main method in Java and C#, rather than a constructor?

Body:
I’m Looking for a definitive answer from a primary or secondary source for why (notably) Java and C# decided to have a static method as their entry point, rather than representing an application instance by an instance of an Application class (with the entry point being an appropriate constructor).

Background and details of my prior research

This has been asked before. Unfortunately, the existing answers are merely begging the question. In particular, the following answers don’t satisfy me, as I deem them incorrect:

There would be ambiguity if the constructor were overloaded. – In fact, C# (as well as C and C++) allows different signatures for Main so the same potential ambiguity exists, and is dealt with.

A static method means no objects can be instantiated before so order of initialisation is clear. – This is just factually wrong, some objects are instantiated before (e.g. in a static constructor).

So they can be invoked by the runtime without having to instantiate a parent object. – This is no answer at all.

Just to justify further why I think this is a valid and interesting question:

Many frameworks do use classes to represent applications, and constructors as entry points. For instance, the VB.NET application framework uses a dedicated main dialog (and its constructor) as the entry point1.

Neither Java nor C# technically need a main method. Well, C# needs one to compile, but Java not even that. And in neither case is it needed for execution. So this doesn’t appear to be a technical restriction. And, as I mentioned in the first paragraph, for a mere convention it seems oddly unfitting with the general design principle of Java and C#.

To be clear, there isn’t a specific disadvantage to having a static main method, it’s just distinctly odd, which made me wonder if there was some technical rationale behind it.

I’m interested in a definitive answer from a primary or secondary source, not mere speculations.

1 Although there is a callback (Startup) which may intercept this.


答:
For Java I'd think the reasoning is simple: When developing Java, the devs knew that most people learning the language would know C/C++ beforehand.

Hence Java not only looks a lot like C/C++ instead of say smalltalk, but also took over idiosynchrasies from C/C++ (just think of octal integer literals). Since c/c++ both use a main method, doing the same for java made sense from that point of view.

I'm pretty sure I remember bloch or someone saying something along this lines about why they added octal integer literals, I'll see if I can find some sources :)


问:
Entry level engineer question regarding memory management
It has been a few months since I started my position as an entry level software developer. Now that I am past some learning curves (e.g. the language, jargon, syntax of VB and C#) I'm starting to focus on more esoteric topics, as to write better software.

A simple question I presented to a fellow coworker was responded with "I'm focusing on the wrong things." While I respect this coworker I do disagree that this is a "wrong thing" to focus upon.

Here was the code (in VB) and followed by the question.

Note: The Function GenerateAlert() returns an integer.

```<code>Dim alertID as Integer = GenerateAlert()
_errorDictionary.Add(argErrorID, NewErrorInfo(Now(), alertID))
</code>```

vs...

```<code> _errorDictionary.Add(argErrorID, New ErrorInfo(Now(), GenerateAlert()))
</code>```

I originally wrote the latter and rewrote it with the "Dim alertID" so that someone else might find it easier to read. But here was my concern and question:

Should one write this with the Dim AlertID, it would in fact take up more memory; finite but more, and should this method be called many times could it lead to an issue? How will .NET handle this object AlertID. Outside of .NET should one manually dispose of the object after use (near the end of the sub).

I want to ensure I become a knowledgeable programmer that does not just rely upon garbage collection. Am I over thinking this? Am I focusing on the wrong things?

答:
Make it work, make it clean, make it SOLID, THEN make it work as fast as it needs to work.

That should be the normal order of things. Your very first priority is to make something that will pass the acceptance tests which shake out of the requirements. This is your first priority because it is your client's first priority; meeting the functional requirements within the development deadlines. The next priority is to write clean, readable code that is easy to understand and can thus be maintained by your posterity without any WTFs when that becomes necessary (it's almost never a question of "if"; you or someone after you  WILL have to go back in and change/fix something). The third priority is to make the code adhere to the SOLID methodology (or GRASP if you prefer), which puts code into modular, reusable, replaceable chunks that again aids maintenance (not only can they understand what you did and why, but there are clean lines along which I can surgically remove and replace pieces of code). The last priority is performance; if code is important enough that it has to conform to performance specs, it's almost certainly important enough to be made correct, clean and SOLID first.

Echoing Christopher (and Donald Knuth), "premature optimization is the root of all evil". In addition, the kind of optimizations you are considering are both minor (a reference to your new object will be created on the stack whether you give it a name in source code or not) and of a type that may not cause any difference in compiled IL. Variable names aren't carried forward into the IL, so since you're declaring the variable right before its first (and probably only) use, I would bet some beer money that the IL is identical between your two examples. So, your coworker is 100% right; you are looking in the wrong place if you're looking at named variable vs inline instantiation for something to optimize.

Micro-optimizations in .NET are almost never worth it (I'm talking about 99.99% of cases). In C/C++, maybe, IF you know what you're doing. When working in a .NET environment, you already are far enough away from the metal of the hardware that there is significant overhead in code execution. So, given that you are already in an environment that indicates you've given up on blistering speed and are instead looking to write "correct" code, if something in a .NET environment really isn't working fast enough, either its complexity is too high, or you should be considering parallelizing it. Here are some basic pointers to follow for optimization; I guarantee you your productivity in optimization (speed gained for time spent) will skyrocket:

Changing the function shape matters more than changing the coefficients - WRT Big-Oh complexity, you can reduce the number of steps that must be executed in an N2 algorithm by half, and you still have a quadratic-complexity algorithm even though it executes in half the time it used to. If that's the lower bound of complexity for this type of problem, so be it, but if there's an NlogN, linear or logarithmic solution to the same problem, you will gain more by switching algorithms to reduce complexity than by optimizing the one you have.

Just because you can't see the complexity doesn't mean it isn't costing you - Many of the most elegant one-liners in the word perform terribly (for example, the Regex prime checker is an exponential-complexity function, while efficient prime evaluation involving dividing the number by all prime numbers less than its square root is on the order of O(Nlog(sqrt(N))). Linq is a great library because it simplifies code, but unlike a SQL engine, the .Net compiler won't try to find the most efficient way of executing your query. You have to know what will happen when you use a method, and thus why a method might be faster if placed earlier (or later) in the chain, while producing the same results.

OTOH, there's almost always a tradeoff between source complexity and runtime complexity - SelectionSort is very easy to implement; you could probably do it in 10LOC or less. MergeSort is a bit more complex, Quicksort more so, and RadixSort even more so. But, as the algorithms increase in coding complexity (and thus "up-front" development time), they decrease in runtime complexity; MergeSort and QuickSort are NlogN, and RadixSort is generally considered linear (technically it's NlogM where M is the largest number in N).

Break fast - If there is a check that can be made inexpensively that is significantly likely to be true and means that you can move on, make that check first. If your algorithm, for instance, only cares about numbers that end in 1, 2, or 3, the most likely case (given completely random data) is a number that ends in some other digit, so test that the number does NOT end in 1, 2, or 3, before making any checks to see whether the number ends in 1, 2, or 3. If a piece of logic requires A&B, and P(A)=0.9 while P(B)=0.1, then check B first, unless if !A then !B (like if(myObject != null && myObject.someProperty == 1)), or B takes more than 9 times longer than A to evaluate (if(myObject != null && some10SecondMethodReturningBool())).

Don't ask any question that you already know the answer to - If you have a series of "fall-through" conditions, and one or more of those conditions are dependent upon a simpler condition that must also be checked, never check both of these independently. For example, if you have a check that requires A, and a check that requires A && B, you should check A, and if true you should check B. If !A, then !A&&B, so don't even bother.

The more times you do something, the more you should pay attention to how it's done - This is a common theme in development, on many levels; in a general development sense, "if a common task is time-consuming or fiddly, keep doing it until you're both frustrated and knowledgeable enough to come up with a better way". In code terms, the more times an inefficient algorithm is run, the more you'll gain in overall performance by optimizing it. There are profiling tools that can take a binary assembly and its debug symbols and show you, after running through some use cases, what lines of code were run the most. Those lines, and the lines that run those lines, are what you should pay the most attention to, because any increase in efficiency you achieve there will be multiplied.

A more complex algorithm looks like a less complex algorithm if you throw enough hardware at it. There are some times where you just have to realize that your algorithm is approaching the technical limits of the system (or the part of it) that you're running it on; from that point if it needs to be faster, you'll gain more by simply running it on better hardware. This also applies to parallelization; an N2-complexity algorithm, when run on N cores, looks linear. So, if you're sure you've hit the lower complexity bound for the type of algorithm you are writing, look for ways to "divide and conquer".

It's fast when it's fast enough - Unless you're hand-packing assembly to target a particular chip, there's always something to be gained. However, unless you WANT to be hand-packing assembly, you must always keep in mind what the client would call "good enough". Again, "premature optimization is the root of all evil"; when your client calls it fast enough, you're done until he doesn't think it's fast enough anymore.


问:
What Java data structure/design pattern best models this object, considering it would perform these methods?

Methods:

```<code>1.  getDistance(CityA,CityB) // Returns distance between two cities
2.  getCitiesInRadius(CityA,integer) // Returns cities within a given distance of another city
3.  getCitiesBeyondRadius(CityA,integer) //Returns cities beyond a given distance of another city
4.  getRemoteDestinations(integer) // Returns all city pairs greater than x distance of each other
5.  getLocalDestinations(integer) //Returns all city pairs within x distance of each other
</code>```

答:
The simplest implementation would be a two dimensional array if the data is known at compile time. Then you could just use some clever construction of what a City object is to figure out which index to use. This would make it pretty hard to extend though.

Another way to do it is to define a class type of something like Distance which contains two end points which are City objects. The idea would be that the order of the City objects shouldn't matter and that when storing them you make sure you're not double counting anything.

The data structure then could use any combinations of ArrayLists or Hashtables indexed by City objects . My preferred method would probably be to keep just an Arraylist<Distance> objects and define helper methods to determine if the given index is relevant to the question at hand. Of course this is potentially slow but on small data sets it's good enough.

For the ___Destinations methods it might be helpful to borrow a functional programming idea and make a method which returns a temporary list of distances with only the target city involved and then search again. But this is in no way necessary.


答:
```<code>public class Map {
    private Hashmap<String, City> cities;
    public Distance getDistance(CityA,CityB) // Returns distance between two cities
    public List<City> getCitiesInRadius(CityA, Distance) // Returns cities within a given distance of another city
    publi List<City> getCitiesBeyondRadius(CityA,Distance) //Returns cities beyond a given distance of another city
    public List<City> getRemoteDestinations(Distance) // Returns all city pairs greater than x distance of each other
    public List<City> getLocalDestinations(Distance) //Returns all city pairs within x distance of each other
 }

public class City {
    private String name;
    private HashMap<City, Distance> distanceTo;
    //getter/setters etc
}
</code>```

You'll need to keep track of distances in both directions, not just one.  Ie, Abernathy to Gruver, and then Gruver will also have Abernathy's distance.

Title: What Java data structure/design pattern best models this object, considering it would perform these methods?

Body:
Methods:

```<code>1.  getDistance(CityA,CityB) // Returns distance between two cities
2.  getCitiesInRadius(CityA,integer) // Returns cities within a given distance of another city
3.  getCitiesBeyondRadius(CityA,integer) //Returns cities beyond a given distance of another city
4.  getRemoteDestinations(integer) // Returns all city pairs greater than x distance of each other
5.  getLocalDestinations(integer) //Returns all city pairs within x distance of each other
</code>```

Body:
public class Map {
    private Hashmap<String, City> cities;
    public Distance getDistance(CityA,CityB) // Returns distance between two cities
    public List<City> getCitiesInRadius(CityA, Distance) // Returns cities within a given distance of another city
    publi List<City> getCitiesBeyondRadius(CityA,Distance) //Returns cities beyond a given distance of another city
    public List<City> getRemoteDestinations(Distance) // Returns all city pairs greater than x distance of each other
    public List<City> getLocalDestinations(Distance) //Returns all city pairs within x distance of each other
 }

public class City {
    private String name;
    private HashMap<City, Distance> distanceTo;
    //getter/setters etc
}

You'll need to keep track of distances in both directions, not just one.  Ie, Abernathy to Gruver, and then Gruver will also have Abernathy's distance.


问:
Developing an analytics's system processing large amounts of data - where to start
Imagine you're writing some sort of Web Analytics system - you're recording raw page hits along with some extra things like tagging cookies etc and then producing stats such as

Which pages got most traffic over a time period

Which referers sent most traffic

Goals completed (goal being a view of a particular page)

And more advanced things like which referers sent the most number of vistors who later hit a goal.

The naieve way of approaching this would be to throw it in a relational database and run queries over it - but that won't scale.

You could pre-calculate everything (have a queue of incoming 'hits' and use to update report tables) - but what if you later change a goal - how could you efficiently re-calculate just the data that would be effected.

Obviously this has been done before ;) so any tips on where to start, methods & examples, architecture, technologies etc.

答:
First, don't assume that a RDMS isn't going to scale.  It might not be the right solution, but saying it won't scale doesn't make sense unless you've considered how your data is going to come into the system, how it's going to be queried and what you eventually want to see from those queries.

Recording raw page hits may or may not be a large dataset.  If you do this in a simple naive way, recording a row for every single hit, it may not scale, but this isn't necessarily the smartest way to record these things.  You are likely going to be working from server logs, which will then distill them into an aggregated form.

Path tracking is likely to be the largest dataset here since you'll need the breadcrumbs from each individual user, but the querying part is important here.  To do this in a sophisticated way, you'll likely be using some application logic, not a raw query.

Unless you have a large number of users, a single RDMS should be able to handle these queries.  The general idea is to keep both the aggregate data and the raw, fine grained level data in different tables. The aggregates provide fast queries with indexes, etc. and the fine grained data can be used to be build new metrics.

Some databases and some BI solutions provide automated ways to do this. Oracle has aggregate persistence for example, but in my work I've found myself writing batch jobs to build aggregates.

Longer term, you'll want to learn about modeling your data dimensionally rather than relationally.  Dimensional models and star schemas are more extensible than a relational model you replicate from a production system and provide a better way to manage the granularity of the data and cached aggregates.

If you have really large datasets, then you'll need to start thinking about using distributed processing, map/reduce, etc.  But you'll save yourself a lot of time if you can manage to use a traditional database in an efficient manner.  Performing complex analytics (i.e., more than simple aggregates such as SUM or AVE) requires a lot of more thinking and expertise in the map/reduce framework than in SQL.


问:
Should a server "be lenient" in what it accepts and "discard faulty input silently"?
I was under the impression that by now everyone agrees this maxim was a mistake. But I recently saw this answer which has a "be lenient" comment upvoted 137 times (as of today).

In my opinion, the leniency in what browsers accept was the direct cause of the utter mess that HTML and some other web standards were a few years ago, and have only recently begun to properly crystallize out of that mess. The way I see it, being lenient in what you accept will lead to this.

The second part of the maxim is "discard faulty input silently, without returning an error message unless this is required by the specification", and this feels borderline offensive. Any programmer who has banged their head on the wall when something fails silently will know what I mean.

So, am I completely wrong about this? Should my program be lenient in what it accepts and swallow errors silently? Or am I mis-interpreting what this is supposed to mean?

The original question said "program", and I take everyone's point about that. It can make sense for programs to be lenient. What I really meant, however, is APIs: interfaces exposed to other programs, rather than people. HTTP is an example. The protocol is an interface that only other programs use. People never directly provide the dates that go into headers like "If-Modified-Since".

So, the question is: should the server implementing a standard be lenient and allow dates in several other formats, in addition to the one that's actually required by the standard? I believe the "be lenient" is supposed to apply to this situation, rather than human interfaces.

If the server is lenient, it might seem like an overall improvement, but I think in practice it only leads to client implementations that end up relying on the leniency and thus failing to work with another server that's lenient in slightly different ways.

So, should a server exposing some API be lenient or is that a very bad idea?

Now onto lenient handling of user input. Consider YouTrack (a bug tracking software). It uses a language for text entry that is reminiscent of Markdown. Except that it's "lenient". For example, writing

```<code>- foo
- bar
- baz
</code>```

is not a documented way of creating a bulleted list, and yet it worked. Consequently, it ended up being used a lot throughout our internal bugtracker. Next version comes out, and this lenient feature starts working slightly differently, breaking a bunch of lists that (mis)used this (non)feature. The documented way to create bulleted lists still works, of course.

So, should my software be lenient in what user inputs it accepts?

答:
Something that seems to be missed here--what are the consequences of failure?

Display a web page?  You should do everything you can to tolerate bad input.  Your choices are to display what you can or throw an error.  The latter course gives the user nothing and thus should only be a last resort as it gives the user a completely useless result, it would be pretty hard for an error to be worse than this.

On the other hand, if it's asking for the target of a Minuteman III you reject "Moscow" as input as it's potentially ambiguous.

OwnerDisplayName: romkyns


答:
What about this:

```<code>public class City{

   private String name;
   private List<AdjCities> adjCities;

   //getters and setters
}

public class AdjCity{
   private int distance;
   private City targetCity;

   public void(int distance, City targetCity){
     this.distance= distance;
     this.city = city;
   }
}
</code>```

So now initialize every city (say, NYC, Boston etc.)  then set the adjacent city to NY (say, Boston is connected to NY with distance '300'). So now initialize 'AdjCity' with 'targetCity' (Boston) and distance is 200. And add this to the list of AdjCity objects.

Now you can put this in a collection and from here I think you can proceed if it makes any sense to you.

Thanks

Body:
What about this:

public class City{

   private String name;
   private List<AdjCities> adjCities;

   //getters and setters
}

public class AdjCity{
   private int distance;
   private City targetCity;

   public void(int distance, City targetCity){
     this.distance= distance;
     this.city = city;
   }
}

So now initialize every city (say, NYC, Boston etc.)  then set the adjacent city to NY (say, Boston is connected to NY with distance '300'). So now initialize 'AdjCity' with 'targetCity' (Boston) and distance is 200. And add this to the list of AdjCity objects.

Now you can put this in a collection and from here I think you can proceed if it makes any sense to you.

Thanks


答:
The only time to worry about optimization early on is when you know you're dealing with something that's either huge or something you know will execute a huge number of times.

The definition of "huge" obviously varies based on what your target systems are like.

Title: Entry level engineer question regarding memory management

Body:
It has been a few months since I started my position as an entry level software developer. Now that I am past some learning curves (e.g. the language, jargon, syntax of VB and C#) I'm starting to focus on more esoteric topics, as to write better software.

A simple question I presented to a fellow coworker was responded with "I'm focusing on the wrong things." While I respect this coworker I do disagree that this is a "wrong thing" to focus upon.

Here was the code (in VB) and followed by the question.

Note: The Function GenerateAlert() returns an integer.

```<code>Dim alertID as Integer = GenerateAlert()
_errorDictionary.Add(argErrorID, NewErrorInfo(Now(), alertID))
</code>```

vs...

```<code> _errorDictionary.Add(argErrorID, New ErrorInfo(Now(), GenerateAlert()))
</code>```

I originally wrote the latter and rewrote it with the "Dim alertID" so that someone else might find it easier to read. But here was my concern and question:

Should one write this with the Dim AlertID, it would in fact take up more memory; finite but more, and should this method be called many times could it lead to an issue? How will .NET handle this object AlertID. Outside of .NET should one manually dispose of the object after use (near the end of the sub).

I want to ensure I become a knowledgeable programmer that does not just rely upon garbage collection. Am I over thinking this? Am I focusing on the wrong things?


答: I would prefer the two line version simply because it is easier to step through with a debugger. A line with several embedded calls makes it more difficult. </p>


问:
Should you create a class within a method?
I have made a program using Java that is an implementation of this project: http://nifty.stanford.edu/2009/stone-random-art/sml/index.html.  Essentially, you create a mathematical expression and, using the pixel coordinate as input, make a picture.  After I initially implemented this in serial, I then implemented it in parallel due to the fact that if the picture size is too large or if the mathematical expression is too complex (especially considering the fact that I made the expression recursively), it takes a really long time.  During this process, I realized that I needed two classes which implemented the Runnable interface as I had to put in parameters for the run method, which you aren't allowed to do directly.  One of these classes ended up being a medium sized static inner class (not large enough to make an independent class file for it though).  The other though, just needed a few parameters to determine some indexes and the size of the for loop that I was making run in parallel - here it is:

```<code>class DataConversionRunnable implements Runnable
    {
        int jj, kk, w;

        DataConversionRunnable(int column, int matrix, int wid)
        {
            jj = column;
            kk = matrix;
            w = wid;
        }

        public void run()
        {
            for(int i = 0; i < w; i++)
                colorvals[kk][jj][i] = (int) ((raw[kk][jj][i] + 1.0) * 255 / 2.0);
            increaseCounter();
        }
    }
</code>```

My question is should I make it a static inner class or can I just create it in a method?  What is the general programming convention followed in this case?

答:
You can use an anonymous class that would look something like this:

```<code>final int column = (something);
final int matrix = (something);
final int wid = (something);

Thread t = new Thread(new Runnable() {
    public void run() {
        for(int i = 0; i < wid; i++)
            colorvals[matrix][column][i] = (int) ((raw[matrix][column][i] + 1.0) * 255 / 2.0);
        increaseCounter();
    }
});

t.run();
</code>```

You'd use something like this (anonymous class) if you are going to use it in only one place in your class. If you want to use it or reference it in more than one place, you use an inner class.

Body:
You can use an anonymous class that would look something like this:

final int column = (something);
final int matrix = (something);
final int wid = (something);

Thread t = new Thread(new Runnable() {
    public void run() {
        for(int i = 0; i < wid; i++)
            colorvals[matrix][column][i] = (int) ((raw[matrix][column][i] + 1.0) * 255 / 2.0);
        increaseCounter();
    }
});

t.run();

You'd use something like this (anonymous class) if you are going to use it in only one place in your class. If you want to use it or reference it in more than one place, you use an inner class.


问:
How do you accept arguments in the main.cpp file and reference another file?
I have a basic understanding of programming and I currently learning C++. I'm in the beginning phases of building my own CLI program for ubuntu. However, I have hit a few snags and I was wondering if I could get some clarification. The program I am working on is called "sat" and will be available via command line only. I have the main.cpp.

However, my real question is more of a "best practices" for programming/organization. When my   program "sat" is invoked I want it to take additional arguments.

Here is an example:

```<code>> sat task subtask
</code>```

I'm not sure if the task should be in its own task.cpp file for better organization or if it should be a function in the main.cpp? If the task should be in its own file how do you accept arguments in the main.cpp file and reference the other file?

Any thoughts on which method is preferred and reference material to backup the reasoning?

答:
There's some personal preference, and some slight design benefits involved. Accepting arguments and passing them to other modules/functions is not an issue. What is at issue is how well the overall architecture will be represented if you split it up, versus if you keep it all in one file.

The main reason for splitting it up should be whether it makes organizational sense to.

If I have a program that deals with Desk and Pig objects, I can split all the Desk related class declaration and definition code into Desk.h and Desk.cpp. Likewise for Pig. If the interfaces to these objects is well-defined, changing how the Desk object is implemented shouldn't change the way your main program runs. But now I'm getting into object-orientated design.

What I'm saying is that if there is a good reason from a design standpoint to split Task up from the main() function, then you should do it. From your post I'm not so sure what you are trying to achieve.

What may help more than my attempt at an answer is Wikipedia's article on software design.


问:
What do you do if you've had a series of bad employers?
So I've had a series of really bad experiences and am wondering what I'm doing wrong.

I started out as a part time programmer at a major university.  I developed a problem with my wrist and asked (nicely) for some help with my ergonomic accomodations.

My boss started screaming at me, then later claimed I screamed at her.  When questioned about it, she just started sobbing.  Luckily, there were others around who heard the screaming and knew I was telling the truth.  She was eventually let go.

My contract went up and I switched jobs, this time to a startup.  Well, we went several months without my getting a development machine.  When the economy tanked, they started asking for insane amounts of overtime.  I complied because I was afraid of having to look for work.  The final straw was they contacted me right before my father's funeral to fix a problem.

I was laid off, didn't receive my final check on time and the company screwed my COBRA up to the point where I couldn't get prescriptions for months.  They recently were fined by the State of X for what they did.  Now, even though I worked my heart out for them and they were willing before being fined, they are refusing to provide a reference.

I took a new job quickly, mainly because I really needed my health insurance set up.  They wanted me to do several months of work in a couple of weeks.  They had no project plan.  Their customers were seriously not doing well, as whole sections of the application would stop working if someone ran a spell check.  Even though they had completely unreasaonble expectations about my work, they were happy to say it would take several months to repair the spell check bug.  There was virtually no training.

They had me interviewing candidates and I selected one.  Apparently, that person was my replacement because I was let go after a few months.

Recently, my former boss called my current employer and made up allegations that I am discouraging people from applying to open positions at his firm, which is insane because I didn't even know they were hiring.

I feel like I have a T-shirt that says, "If you're insane or would like someone to kick around and treat badly, hire me!".

Then again, when I look at some programmers' resumes, I do see horror stories, too.

So are there things I can do differently to avoid these problems?  Is it part of our profession that people do not have standards?  Perhaps it is a personality issue, that resides purely with me?

Has anyone else had a series of bad experiences and turned things around?

答:
You sound like a reasonable guy.  I think you may have just had monumentally bad luck.

There are good companies out there to work for; you just have to find them.  Start wearing suits to your interviews.  Be a professional.  Talk to people who have a job with a good work environment, so that you know what that looks like, and know how people at that kind of company behave.  Then, pick a job that has that environment.

Remember, at an interview, you are interviewing the company as well.

Look for these things:

The ideal job

Has enjoyable and meaningful work

Pays fairly

Has a pleasant, mentally positive, productive work environment

Is challenging, but not excessively stressful

Allows you to do your job well

Has learning opportunities

Has advancement opportunities

Has sensible leadership

Has minimal office politics

Has a reasonable commute

Provides the opportunity to work with motivated, like-minded peers who respect each other

Has adequate work-life balance

Provides an opportunity to work towards long-term goals such as retirement.

I should point out that my current job has most of these things, but it did, in fact, take most of my adult life to find it.  I've been in some pretty screwy work situations as well.

The thing that seemed to make a major difference for me: I went back to school and got my degrees.  I began to be treated differently after that, like I was somebody.


答:
This will be slow.

It seems add operation will eventually require O(N), where N is number of existing cities in the collection. This will be slower and slower as more cities are added.

I can't think of a way to lazy-evaluate the distance. It seems to me all-pair distances must be calculated up front. Maybe someone can offer better suggestions.

Remark. SortedMap Seems wrong. It doesn't allow duplicate keys (two doubles having same value). However, the chances of two pairs of cities with same distance seems remote to me ...

```<code>public class CityCollection
{
    private List<City> cities;

    // Cache distances when cities added, because expensive to calculate
    private Map<Pair<City, City>, double> distances;

    // sorted by pairwise distances
    private SortedMap<double, Pair<City, City>> sortedByDistances;

    public void add(City city)
    {
        if (cities.contains(city)) return;
        for (City oldCity : cities)
        {
            Pair<City, City> pair = new Pair<City, City>(oldCity, city);
            double distnace = getDistance(oldCity, city);
            distances.put(pair, distance);
            sortedByDistances.put(distance, pair);
        }
        cities.add(city);
    }

    // this is possibly very very slow, or very very fast...
    public static double getDistance(City origin, City destination)
    {
        Query q = new Query(
            origin.getCentroid().toString(),
            destination.getCentroid().toString(),
            "GreatCircle");
        // .. wait for query to finish
        return q.distance();
    }

    // implement your other methods here
}
</code>```

Body:
This will be slow.

It seems add operation will eventually require O(N), where N is number of existing cities in the collection. This will be slower and slower as more cities are added.

I can't think of a way to lazy-evaluate the distance. It seems to me all-pair distances must be calculated up front. Maybe someone can offer better suggestions.

Remark. SortedMap Seems wrong. It doesn't allow duplicate keys (two doubles having same value). However, the chances of two pairs of cities with same distance seems remote to me ...

public class CityCollection
{
    private List<City> cities;

    // Cache distances when cities added, because expensive to calculate
    private Map<Pair<City, City>, double> distances;

    // sorted by pairwise distances
    private SortedMap<double, Pair<City, City>> sortedByDistances;

    public void add(City city)
    {
        if (cities.contains(city)) return;
        for (City oldCity : cities)
        {
            Pair<City, City> pair = new Pair<City, City>(oldCity, city);
            double distnace = getDistance(oldCity, city);
            distances.put(pair, distance);
            sortedByDistances.put(distance, pair);
        }
        cities.add(city);
    }

    // this is possibly very very slow, or very very fast...
    public static double getDistance(City origin, City destination)
    {
        Query q = new Query(
            origin.getCentroid().toString(),
            destination.getCentroid().toString(),
            "GreatCircle");
        // .. wait for query to finish
        return q.distance();
    }

    // implement your other methods here
}


问:
Advantages and disadvantages to using XAML/C# or HTML5/JavaScipt for Metro apps?
I was just wondering if there are any major advantages or disadvantages to using either XAML/C# or HTML5/JavaScript for Metro Apps.</p>

答: Both. Because both are being adopted by developers (though not at the same time, what I mean is while some devs are using XAML/C#, some others are using HTML/JS). For those coming from a Web app dev background, it's easier to transition to HTML/JS. And for those aleady familiar with XAML through WPF and Silverlight, it would make sense to carry over the skills to XAML+C#. And as far as results are concerned, both technologies are showing good results. So my guess is both would be equally good in the years to come.</p>


问:
What problems are Java annotations well suited to?
I've been writing in Java and C# for a while, but I'm having a hard time identifying places where using a custom annotation would be advantageous.

I can see that JUnit uses annotations in test classes to identify the order it should run the methods in the test classes, which obviates the need for a configuration of some sort.

What are other examples of problems that annotations solve elegantly?

答:
Depending on the annotations you use and how you run JUnit, JUnit scans the classpath and runs everything with the proper annotations (or, in the old school versions, that implemented a certain interface)

You're right in the sense that annotations are mostly useful for configuration - they're essentially metadata about the method/class.  Here's an example from my work - for some reason I can't remember, we needed to dump objects to a log, but we wanted to filter some of attributes. We made a Loggable annotation that could be applied to individual getters or a class, we then used reflection to determine what to dump and what not to.

I would venture a guess that anything you can do with an annotation you could do with some sort of configuration file. Some annotations are basically formalized comments (e.g., @Deprecated).  So the fact you can't come up with common cases isn't really surprising.


问:
Is working on a large project a good or a bad thing in the long run?
In a large project you only get to use the technology necessary for that project; smaller projects come and go, and you need to learn more technologies.

On the other hand large projects are usually complex and thus hard; if you are used to hard projects then you should manage to perform well on smaller projects.

So, in the long term is it better to work on small or on large projects?

答:
I think it is very useful to work on a large project. As one learns a lot of aspects of Software Engineering in large projects, which includes but is not limited to:

Organizing code for

Reusability

Maintainability

Extensibility

Team work

Project Management

When you say you get limited to technologies, you probably do, but you can switch projects/jobs/roles once the interesting parts of the project is done. This is usually when the project has gone into production. After a cycle or two of updates you might start getting bored with the technology

The experience on a product is very different. One has to think of a lot of aspects for an update e.g.,

Backward Compatibility

Data Migration

Technologies come and go anyways but the experience of building a large project will always be useful. That said, whenever you are going to venture with a new technology, having experience of having built small projects in the technology will act for risk mitigation when you get to build a large project in it.


问:
Does Sublime's "minimap" improve productivity?
I'm a pretty big fan of Sublime.  One of my favorite features is the ability to scroll through your file by using the compressed image of your text on the upper right hand corner (minimap).  My gut feeling is this does positive things for productivity:

Does having this minimap to scroll through actually improve productivity?

P.S. - Side question: Did Sublime invent this idea, or did they take it from another text editor?

答:
I find myself using it in three situations:

When I need to make changes throughout a file, like replacing a name and reviewing the changes to make sure they're correct. The minimap gives me an idea of how much of the file I have left work through.

As a replacement for the vertical scroll bar. The minimap is easier to click, because it's wider.

If some plugin (like SublimeClang for C/C++) can highlight problems, the minimap lets me see them on an almost file-wide level and allows me to quickly navigate to them.

The actual productivity gain is rather small, but I like the feature. I don't have the feeling that it really gives an overview to the code since the text is rather uniform. But I suppose if you have distinctive structures in your source or can somehow color-code it, the minimap could actually help.


答:
Annotations are just metadata, personally I prefer annotations to xml configurations, but don't completely right xml off. My advice use annotations whenthat wouuld make metadata usage more clear and transparent. As an example take a look at JPA annotations, isn't it better to say that your class is an Entity than it is to right an xml file about it and how it relates to other @entities. Annother example Spring MVC @Controllers and @RequestMapping , it's so much easier to find out what the class is and what it does by simply looking at it, not having to go through a pletora of xml files. It is important to note however that too many annotations make the code difficult to read and should be avoided when possible. My advice, go with your gut but always try to make your code readable.

Hope that helps,

Peter

P.S. I don't know what Junit does, I have never looked at it's code, but I assume there is some sort of a classpath scanner

Title: What problems are Java annotations well suited to?

Body:
I've been writing in Java and C# for a while, but I'm having a hard time identifying places where using a custom annotation would be advantageous.

I can see that JUnit uses annotations in test classes to identify the order it should run the methods in the test classes, which obviates the need for a configuration of some sort.

What are other examples of problems that annotations solve elegantly?


问:
Design Pattern for Skipping Steps in a Wizard
I'm designing a flexible Wizard system that presents a number of screens to complete a task.  Some screens may need to be skipped based on answers to prompts on one or more previous screens.

The conditions to skip a given screen need to be editable by a non-technical user via a UI.  Multiple conditions need only be combined with and.

I have an initial design in mind, but it feels inelegant.  I wonder if there's a better way to approach this class of problem.

Initial Design

UI

where

The first column allows the user to select a question from a previous screen.

The second column allows the user to select an operator applicable to the type of question asked.

The third column allows the user to enter one or more values depending on the selected operator.

Object Model

```<code>public enum Operations { ... }
public class Condition
{
    int QuestionId { get; set; }
    Operations Operation { get; set; }
    List<object> Parameters { get; private set; }
}

List<Condition> pageSkipConditions;
</code>```

Controller Logic

```<code>bool allConditionsTrue = pageSkipConditions.Count > 0;
foreach (Condition c in pageSkipConditions)
{
    allConditionsTrue &= Evaluate(previousAnswers, c);
}

// ...

private bool Evaluate(List<Answers> previousAnswers, Condition c)
{
    switch (c.Operation)
    {
        case Operations.StartsWith:
            // logic for this operation
        // etc.
    }
}
</code>```

答:
One improvement:

Simply have  a method in Condition.evaluate(List<Answers> previous) and implement the logic there, since it should be invariant. Scratches the switch statement.

Another comment: You might want to consider allowing multiple conditions per question ID. in the current model you'll have trouble jumping to different questions based on criteria (i.e., jump to 34 if I enter <4, jump to 92 otherwise, etc).   You might also want to consider having conditions be part of Question or some mediating object (QuestionConditions or what have you)

Otherwise looks good to me, writing wizards sucks, keep it at simple as possible.


答:
Size doesn't matter, success does!

Working on projects with valuable mentors that can accelerate your judgement and experience and that are successful at pleasing customers is the most important thing you can focus on career wise.

Working on project after project that is a failure will teach you things but in a backwards way that takes a very long time to understand. Working on long drawn out projects that are failing is the same thing.

Size of the project doesn't mean complex or simple. It doesn't mean more or less new things to learn. Complex and "hard" projects are usually due to mismanagement, overly complex design and architecture and the like, this can apply to multi-week projects as well as multi-year projects.

Good Enough and YAGNI

There are a great number of projects today that don't have long shelf lives. There are web projects that may only be in production for a few weeks or months depending on the lifecycle of the need of the software. Think promotional micro-sites that are temporal in nature will be thrown away and never updated or maintained.

Learning how to scale down your Architecture Astronaut tendencies and do just enough to scratch an itch is a very rare and valuable skill today.

Not that Good Enough and YAGNI don't apply to longer lifecycle projects, but scaling down process and methodology is much harder than scaling up.

Specialization is for insects

A human being should be able to change a diaper, plan an invasion,
  butcher a hog, conn a ship, design a building, write a sonnet, balance
  accounts, build a wall, set a bone, comfort the dying, take orders,
  give orders, cooperate, act alone, solve equations, analyze a new
  problem, pitch manure, program a computer, cook a tasty meal, fight
  efficiently, die gallantly. Specialization is for insects.
  -Robert A. Heinlein

Apply the above to software development and you won't go wrong. Being competent at many things will insulate you from fads and fetishes in the industry and ensure you are more employable than people who are one trick ponies.

Title: Is working on a large project a good or a bad thing in the long run?

Body:
In a large project you only get to use the technology necessary for that project; smaller projects come and go, and you need to learn more technologies.

On the other hand large projects are usually complex and thus hard; if you are used to hard projects then you should manage to perform well on smaller projects.

So, in the long term is it better to work on small or on large projects?


问:
Why OOP is enforced in Java and C#?
In many other languages like C++ and Javascript, OOP is optional. Procedural code is ok. But in languages like Java and C#, OOP is somewhat enforced. Everything is to be a part of a class or an object. What are the benefits?</p>

答:
One point which hasn't been mentioned is that in many garbage-collection-based object-oriented framework, it is absolutely 100% imperative that the system know the whereabouts of every single object reference--not just every object, but every reference as well--at any time when garbage collection may occur; if there is any thread Th in which the system doesn't know the whereabouts of every single object reference and garbage-collection becomes necessary, all other threads must wait for thread Th to reach a point where the system knows where all its object references are.

The above requirement is much stricter than anything which exists for C or C++.  In C or C++, one can construct a union which combines an integer numeric type with a pointer, and provided the code keeps track of whether the thing holds an integer or a pointer, it won't matter whether the runtime framework can tell what type the thing is.  Such an approach wouldn't work in a garbage-collected language.  If interpreting the content of a union as a pointer would reference an object which is being relocated, then it's absolutely imperative that the content of the union be updated to hold the new address if the last thing stored there was a pointer, but it's equally imperative that it be left alone if it's supposed to be holding an integer.  There's simply nothing the runtime can do safely if it can't require object-references be stored in storage locations of object-reference type and nowhere else.

Title: Why OOP is enforced in Java and C#?


问:
What should be in a coding standard?
What should be in a good (read:useful) coding standard?

Things the code should have.

Things the code shouldn't have.

Should the coding standard include definitions of things the language, compiler, or code formatter enforces?

What about metrics like cyclomatic complexity, lines per file, etc?

答:
Some standards I like (I know there is a lot of them, but that's those I prefer):

80% unit tests coverage

Collective ownership of the code (write code to be read by your team mates, not the compiler)

Write comments. Write what you would say to a newcomer.

Keep it simple

Title: What should be in a coding standard?


问:
Database source control
Should database files(scripts etc.) be on source control?
If so, what is the best method to keep it and update it there?

Is there even a need for database files to be on source control since we can put it on a development server where everyone can use it and make changes to it if needed. But, then we can't get it back if someone messes it up.

What approach is best used for databases on source-control?

答:
I will also like to bring a monitoring tool that can be also  to used as data versioning tool. The tool I am talking about is MONyog, actually it is an MySQL monitoring tool but with a little hack we can easily use it as data versioning.

But before going further i will quote that it will not be advisable to put up whole of the database for versioning.  It is be real killer to track change for a particular set of data.

MONyog has a feature called CSO (Custom SQL Objects), which can monitor the change in particular set of data. Adding a CSO is described here. Now in MONyog's monitor history section you can get a the changes over a period of time. Best, it gives a visual report in html page. The report will look something like this

Title: Database source control


答:
I would like to make a few points not yet mentioned in Jarrod's and Ozair's otherwise good answers:

Large projects tend to have a longer lifecycle, thus maintainability is a key concern. (Small projects can also live long, but IMHO it is less likely... moreover these often grow larger over time.) In small projects, you are less likely to (be forced to) learn how to write maintainable (= modular, clean, testable, SOLID) code.

Large projects tend to involve larger development teams too, plus a lot of other people (various managers, QA personnel, technical writers, etc.) which means communication (on many levels) is more essential than in a small project.

Large projects tend to slow down over time (due to a larger team, usually part of a large organization, and the long lifecycle), getting more and more into maintenance mode. This may be less glamorous, nevertheless an important part of the SDLC. However, this also means that chances to learn new technologies get limited. (OTOH, as suggested above, there is an awful lot more to SW development than technology...) And usually it also means more bureaucracy and less agility :-(


问:
How do you keep track of the meaning of your SQL fields?
The more SQL fields I add to my tables and the more primary/foreign keys I add the more I lose the overview for specific fields for certain scenarios like Get/Add/Delete/Update data.

I use SQL Management Studio (SQL Server) to design my database in the database diagram designer.

Maybe there is a better tool or good approach how to keep track of the meaning of all those fields?

答:
How about a logical semantically correct naming system that avoids duplication, tautology and abbreviations?

That and a Glossary and a logical / physical ER diagram of the database, preferably hosted on a Wiki of some sort, is about all you can do.

Plus what Jason Holland says in the comment below! :-)


答: You can also add them as hints for static and run time code analysis tools. e.g. @ThreadSafe, @Immutable and so on. These give hints to the developer as to how the object should be treated/behave and the tooling can often give some level of confidence on that.</p>


问:
How Can I Know Whether I Am a Good Programmer?
Like most people, I think of myself as being a bit above average in my field.  I get paid well, I've gotten promotions, and I've never had a real problem getting good references or getting a job.

But I've been around enough to notice that many of the worst programmers I've worked with thought they were some of the best.  Bad programmers who are surrounded by other bad programmers seem to be the most self-deluded.

I'm certainly not perfect.  I do make mistakes.  I do miss deadlines.  But I think I make about the same number of bonehead moves that "other good programmers" do.  The problem is that I define "other good programmers" to mean "people who are like me."

So, I wonder, is there any way a programmer can make some sort of reasonable self-evaluation?  How do we know whether we are good or bad at our jobs?

Or, if terms like good and bad are too ill-defined, how can programmers honestly identify their own strengths and weaknesses, so that they can take advantage of the former and work to improve the latter?

答:
My answer will be politically incorrect. However, I am actually a founder of a start up and my job is to hire the best programmers.

How do I know which people will be good programmers or can be good programmers?

1 word: IQ.

IQ is for programming as height is for basket ball players.

I would put Math skills as another more politically correct indicators. My computer science teachers told me that there is one criteria that correctly predict who will succeed at programming courses. High School Math scores. Those are effectively IQ anyway.

This may come as a surprise. We are told that programming is a college degree job. Guess what, I don't care about degree. I care only about 3 things.

Programming skills (that can be tested).

Aptitude.

Common sense (not too low) people's skills.

Unfortunately IQ only measures one thing. So I do some tests.

I ask people questions. Simple question I expect elementary school kid should be able to answer.

I ask questions like:

What's the distance between short and long hand of the clock at 7:35

If I go from Jakarta to Semarang and want to maintain 60km/hour speed. Then on first 2 hours I drive 100km/hour. How fast I should go for the rest of the trip so that my AVERAGE speed is 60km/hour?

If you look carefully those questions do not require creativity at all. Only common sense. Any elementary school kids with IQ can answer that.

MOST college graduate cannot. Now imagine if someone cannot answer that? Can he program? Think about it. How often you will have to specify what he should do?

You can also ask questions like Microsoft that do require creativity. You can ask questions on how to weigh 8 balls in a balance scale to know which one is the heaviest. The problem with such questions is that it involves luck. However, some are quite easy it should be a minimum requirement.

Getting an awesome programmer can improve morales of other programmers. Getting one lawsy programmers can lower everyone else' morale.

After people can answer questions like that, which is very easy, I would make them write some google jam code.

Good programmers can solve google jam code and can predict which problems are easier.

OwnerDisplayName: Kristopher Johnson


答:
SQL Management Studio has the ability to add a Description for columns, but I've never found it useful, ever. I've also tried to get work to use docs, wikis and what-have-you's to document DB structure. After enough time, nobody bothers though. Release dates won't wait for anything.

A descriptive, consistent naming scheme won't fail you. Don't be afraid to use longer and descriptive column names if you feel the need, it's better to ensure future-you can make sense of the structure.

Currently I'm working a a 1600+ column DB that is a nightmare of inconsistent naming; so stick to your style!

A suggestion:

name the primary key column to include it's purpose, so not "ID", but "ClientID". Makes reading queries easier.

decide and stick to table names being singular or plural (i.e. tblClient vs tblClients)

My logical self prefers the singular

prefer to group similar tables together, i.e. prefix lookup/static tables with tblLUT / lookup_

the same goes for grouping Clients, Jobs, Assets, Cheezeburgers and similar

use stored procedures and custom views, a lot of them, to retrieve your data

this normalizes your data access, providing a higher layer of data access

On a semi-related note, I recently found an alternative SQL server tool, with this nifty feature to generate code classes based on your table structures, taking a data reader in the constructor, makes for real handy work. It has made me realize that naming tables and fields without tbl and f prefixes is kind of nice for tools like these. (SQL Anywhere by Atlantis Interactive)

Title: How do you keep track of the meaning of your SQL fields?

Body:
The more SQL fields I add to my tables and the more primary/foreign keys I add the more I lose the overview for specific fields for certain scenarios like Get/Add/Delete/Update data.

I use SQL Management Studio (SQL Server) to design my database in the database diagram designer.

Maybe there is a better tool or good approach how to keep track of the meaning of all those fields?


问:
Is it okay to use a language that isn't supported by your company for some tasks?
I work for a company that supports several languages: COBOL, VB6, C#, and Java. I use those languages for my primary work, but I often find myself coding some minor programs (e.g. scripts) in Python because I find it to be the best tool for that type of task.

For example: an analyst gives me a complex CSV file to populate some DB tables, so I use Python to parse it and create a DB script.

What's the problem?

The main problem I see is that a few parts of these quick and dirty scripts are slowly gaining importance and:

My company does not support Python

They're not version controlled (I back them up in another way)

My coworkers do not know Python

The analysts have even started to reference them in emails ("launch the script that exports..."), so they are needed more often than I initially thought.

I should add that these scripts are just utilities that are not part of the main project; they simply help to get trivial tasks done in less time. For my own small tasks they help a lot.

In short, if I were a lottery winner to be in a accident, my coworkers would need to keep the project alive without those scripts; they would spend more time fixing CSV errors by hand, for example.

Is this a common scenario? Am I doing something wrong? What should I do?

答:
When you are told to write code doing sth., the language is usually specified or implied (the rule in corporations).

But when you have to do some one-shot task, such as import data into DB, you are free to choose the tool that in your opinion fits the best, because you have to do something correct and fast, and the result is important, not the tools.

So, I would use that rule:

1) If you are told to do some task, such as data import, I would use the tools/language/etc. that would be the most convenient for me and would be the fastest for the task.

2) If you are told to write tool doing some task, such as import some data, I would discuss what language/tool to use with the manager (with exception when I use language that is implied standard, for example when company uses [almost] only Java).

3) If the task seemed to be one-shot, but it became repeatable, you should talk with the manager to change it from 1) to 2) and re-write from your preferred to company-supported language.

ContentLicense: CC BY-SA 4.0


问:
FizzBuzz - really?
When it comes to "interview test" questions, the subject of FizzBuzz often comes up. There is also a Coding Horror post about it.

Now, if you bother reading sites such as this, you are probably less likely to be in the demographic of programmers who would find FizzBuzz anything but trivial.

But is it really true that 99% of programmers will struggle with it?

Really?

What is the evidence to back this up?

Some real-life examples would be very helpful in answering this question.

答:
All you need to do is search on FizzBuzz. There was a huge wave of blog posts on it. Generally speaking the blogger said "I told people to write it in [some language] and here are the kinds of mistakes they made:" and then listed some pitfalls. The fun starts in the comments where people say "ha! that's trivial in [some other language], all you have to write is this:" followed by code. The next comment invariably finds bugs in that first one. Seems like some very good devs don't get it right the first time, in any language. Some of the errors:

I asked for 1 to 100 and you did 1 to 99 or 0 to 99

messing up on whether to print the number along with fizz and/or buzz

disagreements on "fizzbuzz" vs "fizz-buzz"

missed optimizations, like comparing twice when once would do

lots more

When I'm hiring, I ask people to code at the whiteboard for me, nothing anywhere near that complicated (I know, you don't think it's complicated) and many candidates fail utterly. I mean like writing vb-style If, Then, End If but putting braces as well (just to be on the safe side I guess) or writing C# (and asking first, C#?) but having not one semi colon anywhere. Don't start me on logic errors!

Title: FizzBuzz - really?


答:
As others pointed out, annotations are metadata about classes / properties / methods. In general, I find them most useful when data needs to be transformed between the Java domain and another domain or format, such as

a database (this is what e.g. Hibernate / JPA is dealing with, using annotations heavily)

an Excel sheet

a legacy mainframe system

The latter two are real examples from the project I am working on.

Another, related task is data validation. We use the annotations of Hibernate Validator (which is an implementation of JSR 303 - Bean Validation) to validate critical pieces of the data received from the above mentioned mainframe, before letting it enter our domain.

As others noted, all the information represented by annotations could in theory be represented in other forms, e.g. in distinct config files (in XML or other format). However, often it is just so much more convenient to have the annotations right there in the code, next to the entity it refers to. Typically (like in the above examples) the metadata represented by annotations is tightly tied to the code. So - once created - it very rarely changes independently of the corresponding code itself. So keeping it physically together with the code makes it cleaner and more maintainable.


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

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

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

答:
The reason NOT to use a global (or singleton) is that even though you initially expect to only have one value, it's often surprisingly useful to be able to use the same code multiple times in the same program, for instance:

to compute what WOULD happen if the interest rate was different

to have some components depend on the US interest rate and some components depend on the UK interest rate

I would make the interest rate a member of the "financial instrument" class, and accept that you have to pass it in to any member classses (either per-calculation, or giving them a pointer/hook to it on construction).

Title: What if globals make sense?


答:
Both are going to run on WinRT (aka trimmed down version of Windows 8 which is used on MS Surface device).

It will totally depend on developers preference . Thus, developers with HTML5/JS experience will be equally powered to develop for Window 8.

Title: Advantages and disadvantages to using XAML/C# or HTML5/JavaScipt for Metro apps?

Body: I was just wondering if there are any major advantages or disadvantages to using either XAML/C# or HTML5/JavaScript for Metro Apps.</p>


答:
I would suggest to group your tables in logical domains and visualize them on a poster. You may created and prepare printable file them with the help of ER studio/SSMS.

Most importantly, naming of columns need to be closely related to domain to avoid naming further ambiguity in long run.


答:
Quick answer would be: It depends.

Both big/small projects has their specific flavors for developers involved in it. The main difference is in project management approach and scope of the project. From developer point of view, it is more of building infrastructure code to handle common use cases to support your project in long run.

Smaller projects tend to be one-man team with very little design time and aggressive deadline :)


答:
My Preference is to work on a complete project either it is small or large.
We should get complete understanding of the project, get involved right from the beginning till its sunset.  Also we should play multiple roll in the project so that we can understand a Project Life Cycle Better.

With Respect to Time Frame it is better to start with small projects and learn them completely, later go for Bigger/Large Project and try to learn them.  Usually it will be different to learn Large Project.  But if you have intial experience with Small Projects that will help you to understand Large Project Quickly

In Summary : Start with small projects, learn thoroughly and then settle in large projects.


答: I can partially answer your sidequestion: DrRacket (the development environment of Racket; formerly known as DrScheme and PLT Scheme respectively) has a contour view that works exactly the same.</p>

Title: Does Sublime's "minimap" improve productivity?

Body:
I'm a pretty big fan of Sublime.  One of my favorite features is the ability to scroll through your file by using the compressed image of your text on the upper right hand corner (minimap).  My gut feeling is this does positive things for productivity:

Does having this minimap to scroll through actually improve productivity?

P.S. - Side question: Did Sublime invent this idea, or did they take it from another text editor?


问:
Is it worth making a commit solely to resolve non-critical typos?
If I come across a non-critical typo in code (say, an errant apostrophe in a print(error) statement), is it worth making a commit to resolve that error, or should it simply be left alone?

Specifically, I'm curious about weighing the gumming-up of the commit log against the value of resolving these non-critical typos. I'm leaning toward resolving them. Am I being pedantic?

答:
Does your change management process allow it?

In my environment, every commit I make must be tied back to a change request which has been requested either by the business users or a mandatory system-level change, complete with the corresponding end-user testing processes. A simple typo like you're describing probably wouldn't be logged as either of those (I've found typos & grammatical errors in one of my apps which existed for over 4 years without anyone noticing), so if/when the auditors came calling I'd have a very difficult time explaining myself.

I would save a change like you're describing (and actually have one, as a matter of fact - a method name is mis-spelled and I just discovered it) for a time when I have a "real" change that needs to be made as well and put "fixed various typos" in the log.


答:
In my last round of hiring I had 3 construction workers with 0, I repeat zero, programming education or experience apply for a software developer position.*
So that's the bottom of the barrel. If you assume a normal distribution of skill, then you can see how the average skill level will be quite low and even 'above average' (amongst applicants) will still be relatively bad.

Now, if you're fizzbuzzing only the applicants that had what appeared to be some programming ability, you'll find that you now have:

liars

buzzword enthusiasts (I read an article about .NET once)

bad actual programmers

people who used a technology to complete a project, but didn't learn about it (see fizzbuzz questions about idisposable to identify these)

Additionally, some 'fizzbuzz' questions that I've seen are domain specific. You can progressively develop with a language/framework x for a number of years (hence z years experience with x) and not have come across certain parts of it (library developers not knowing much about UI component development for eg.)

Likewise, lots of developers do maintenance development these days, so their architecture/design skills may be weak in some areas.

Now, I'm not sure if 99% is accurate, but IME it's still pretty high. At least in the 80% range.

* No, we didn't call or even give a second look at these applications.

Title: FizzBuzz - really?

Body:
When it comes to "interview test" questions, the subject of FizzBuzz often comes up. There is also a Coding Horror post about it.

Now, if you bother reading sites such as this, you are probably less likely to be in the demographic of programmers who would find FizzBuzz anything but trivial.

But is it really true that 99% of programmers will struggle with it?

Really?

What is the evidence to back this up?

Some real-life examples would be very helpful in answering this question.


答:
Your .cpp code files all compile into the same binary/objects, so separating files is merely a convenience for development, making code modular. After parsing the command line parameters, you may decide what calls to perform in your application.

You iterate through application arguments via the argv[] array passed to your main() entry point.

```<code>#include <iostream>

int main(int main, char* argv[])
{
        // Check the number of parameters
        if (argc < 2) {
                // Tell the user how to run the program
                std::cerr << "Usage: " << argv[0] << " NAME" << std::endl;
                /* "Usage messages" are a conventional way of telling the user
                 * how to run a program if they enter the command incorrectly.
                 */
                return 1;
        }
        // Print the user's name:
        std::cout << argv[0] << "says hello, " << argv[1] << "!" << std::endl;
        return 0;
}
</code>```

As for best practices, it's best not to reinvent the wheel by using a command line parser library as answered here.

Title: How do you accept arguments in the main.cpp file and reference another file?

Body:
I have a basic understanding of programming and I currently learning C++. I'm in the beginning phases of building my own CLI program for ubuntu. However, I have hit a few snags and I was wondering if I could get some clarification. The program I am working on is called "sat" and will be available via command line only. I have the main.cpp.

However, my real question is more of a "best practices" for programming/organization. When my   program "sat" is invoked I want it to take additional arguments.

Here is an example:

```<code>> sat task subtask
</code>```

I'm not sure if the task should be in its own task.cpp file for better organization or if it should be a function in the main.cpp? If the task should be in its own file how do you accept arguments in the main.cpp file and reference the other file?

Any thoughts on which method is preferred and reference material to backup the reasoning?

Body:
Your .cpp code files all compile into the same binary/objects, so separating files is merely a convenience for development, making code modular. After parsing the command line parameters, you may decide what calls to perform in your application.

You iterate through application arguments via the argv[] array passed to your main() entry point.

#include <iostream>

int main(int main, char* argv[])
{
        // Check the number of parameters
        if (argc < 2) {
                // Tell the user how to run the program
                std::cerr << "Usage: " << argv[0] << " NAME" << std::endl;
                /* "Usage messages" are a conventional way of telling the user
                 * how to run a program if they enter the command incorrectly.
                 */
                return 1;
        }
        // Print the user's name:
        std::cout << argv[0] << "says hello, " << argv[1] << "!" << std::endl;
        return 0;
}

As for best practices, it's best not to reinvent the wheel by using a command line parser library as answered here.


问:
What are the advantages of Ceylon over Java?
Looking for the recent and powerful upcoming programming languages over net, I came across Ceylon. I dropped in at ceylon-lang.org and it says:

Ceylon is deeply influenced by Java. You see, we're fans of Java, but we know its limitations inside out. Ceylon keeps the best bits of Java but improves things that in our experience are annoying, tedious, frustrating, difficult to understand, or bugprone.

What are the advantages of Ceylon over Java?

答:
As far as I noticed, one of the biggest difference between Ceylon and other "hobby-created" JVM languages is that it's gonna be backed by Red Hat / JBoss. So it's gonna get a really nice tooling set integrated into JBoss Tools / Developer Studio, good interactions with JBoss AS / Gatein Portal and all the Midleware / JEE 6 / BRMS. So you might at some poing develop full fledged Ceylon applications in JSF, very productive portlets with a PHP "change and refresh cycles" and what not.

As most JVM-based languages, I don't see it as a replacement for Java for projects needing huge code-bases, but for some small to mid size projects, especially once which are very modular (like CRUD-intensive, portlets, etc). I think it's gonna be extremely well received in the web world, especially by JBoss fans.


问:
What is block level design in context of mobile application?
I was wondering if anyone can give me some direction related to "Block level design" in context of mobile application? Recently I saw a video in my university and a professional mentioned about building block level design of applications, since then it has stuck in my brain!

It would be really helpful if someone can share their knowledge.

答:
A block level design is something which presents all the functional parts of your application in a visual format.
     In case of Block level diagram of Android application you can start with android architecture

and then from the applications block onwards you can have your application, then as per the responsibilities make separate blocks for related activities along with their respective UI wherever applicable (UI is not needed in case of services, broadcast receiver etc) in xml file. And your block diagram is ready.

Same process you can follow for your required mobile platform.

Note that the block diagram gives overall view of application. so no need to have detail description of every aspect.


问:
What do you do if you've had a series of bad employers?
So I've had a series of really bad experiences and am wondering what I'm doing wrong.

I started out as a part time programmer at a major university.  I developed a problem with my wrist and asked (nicely) for some help with my ergonomic accomodations.

My boss started screaming at me, then later claimed I screamed at her.  When questioned about it, she just started sobbing.  Luckily, there were others around who heard the screaming and knew I was telling the truth.  She was eventually let go.

My contract went up and I switched jobs, this time to a startup.  Well, we went several months without my getting a development machine.  When the economy tanked, they started asking for insane amounts of overtime.  I complied because I was afraid of having to look for work.  The final straw was they contacted me right before my father's funeral to fix a problem.

I was laid off, didn't receive my final check on time and the company screwed my COBRA up to the point where I couldn't get prescriptions for months.  They recently were fined by the State of X for what they did.  Now, even though I worked my heart out for them and they were willing before being fined, they are refusing to provide a reference.

I took a new job quickly, mainly because I really needed my health insurance set up.  They wanted me to do several months of work in a couple of weeks.  They had no project plan.  Their customers were seriously not doing well, as whole sections of the application would stop working if someone ran a spell check.  Even though they had completely unreasaonble expectations about my work, they were happy to say it would take several months to repair the spell check bug.  There was virtually no training.

They had me interviewing candidates and I selected one.  Apparently, that person was my replacement because I was let go after a few months.

Recently, my former boss called my current employer and made up allegations that I am discouraging people from applying to open positions at his firm, which is insane because I didn't even know they were hiring.

I feel like I have a T-shirt that says, "If you're insane or would like someone to kick around and treat badly, hire me!".

Then again, when I look at some programmers' resumes, I do see horror stories, too.

So are there things I can do differently to avoid these problems?  Is it part of our profession that people do not have standards?  Perhaps it is a personality issue, that resides purely with me?

Has anyone else had a series of bad experiences and turned things around?

答:
I think you need to think about leaving before they force you to.  You'll look better to other employers, and it conveys confidence ("I don't have to take your crap.").

Also research the job before you even go for the interview.  Avoiding start-ups might also be helpful, as those are very hit or miss.


答:
Well, there's a formal pattern from Fowler that describes what you're doing right here. I've used it to design wizards that had branches as well (though I remember his decsription/documentation of that pattern being much better).

That said, if you take a step back and really look at what you're describing... it looks remarkably like a state machine. Those are well documented in many many places but they come in different flavours through implementation details. Most notable of those:

central control ie. some class manages the state transition logic (this looks similar to what you've designed already)

distributed control ie. each state knows of the transitions that leave it, and calls a state change on the parent whose state they implement

Title: Design Pattern for Skipping Steps in a Wizard

Body:
I'm designing a flexible Wizard system that presents a number of screens to complete a task.  Some screens may need to be skipped based on answers to prompts on one or more previous screens.

The conditions to skip a given screen need to be editable by a non-technical user via a UI.  Multiple conditions need only be combined with and.

I have an initial design in mind, but it feels inelegant.  I wonder if there's a better way to approach this class of problem.

Initial Design

UI

where

The first column allows the user to select a question from a previous screen.

The second column allows the user to select an operator applicable to the type of question asked.

The third column allows the user to enter one or more values depending on the selected operator.

Object Model

```<code>public enum Operations { ... }
public class Condition
{
    int QuestionId { get; set; }
    Operations Operation { get; set; }
    List<object> Parameters { get; private set; }
}

List<Condition> pageSkipConditions;
</code>```

Controller Logic

```<code>bool allConditionsTrue = pageSkipConditions.Count > 0;
foreach (Condition c in pageSkipConditions)
{
    allConditionsTrue &= Evaluate(previousAnswers, c);
}

// ...

private bool Evaluate(List<Answers> previousAnswers, Condition c)
{
    switch (c.Operation)
    {
        case Operations.StartsWith:
            // logic for this operation
        // etc.
    }
}
</code>```


问:
Confusion of scope of a variable: Is Global Variable a solution?
I am newly learning C Programming.

When we have a C Program with lot of functions, parameter passing, calling and all - It becomes a great problem as to which variable must be declared where.

My question is: If I declare all the variables (or atleast the variables that are confusing me) as Global Variables - my problem will be solved - but is that a Good Practice?

答:
No, this causes far more problems than it solves. It is VERY BAD practice, and a classic anti-pattern. Don't do it.

One of the main problems is that it is much more difficult to discover how a global variable gets changed, and what the impacts of changes are, than when you have values which isolated from the rest of the code by passing them into functions.


答:
no it is not a good practice as it will polute the global namespace (eventually you'll run out of names) and globals can be changed anywhere

if you have a set of parameters passed  togheter often you can combine them in a struct that you can pass (pass a pointer if it becomes too big to be copied around)

Title: Confusion of scope of a variable: Is Global Variable a solution?

Body:
I am newly learning C Programming.

When we have a C Program with lot of functions, parameter passing, calling and all - It becomes a great problem as to which variable must be declared where.

My question is: If I declare all the variables (or atleast the variables that are confusing me) as Global Variables - my problem will be solved - but is that a Good Practice?


答: I don't remember any good pattern for global variable, but this is definitely not. And if you having too much parameters it's a sign that you probably need refactor your function.</p>


问:
Is this method of writing Unit Tests correct?
I have created a small C# project to help me learn how to write good unit tests. I know that one important rule of unit testing is to test the smallest 'unit' of code possible so that if it fails you know exactly what part of the code needs to fixed. I need help with the following before I continue to implement more unit tests for the project:

If I have a Car class, for example, that creates a new Car object which has various attributes that are calculated when its' constructor method is called, would the two following tests be considered as overkill? Should there be one test that tests all calculated attributes of the Car object instead?

```<code>    [Test]
    public void CarEngineCalculatedValue()
    {
        BusinessObjects.Car car= new BusinessObjects.Car();
        Assert.GreaterOrEqual(car.Engine, 1);
    }

    [Test]
    public void CarNameCalculatedValue()
    {
        BusinessObjects.Car car= new BusinessObjects.Car();
        Assert.IsNotNull(car.Name);
    }
</code>```

Should I have the above two test methods to test these things or should I have one test method that asserts the Car object has first been created and then test these things in the same test method?

答:
To me, a unit test case (method) should test a single test scenario. This may require multiple asserts, and IMO this is fine. As both of your test methods are exercising the same scenario (creating an object and ensuring it is in a consistent initial state), I would merge them into a single test case.

As to how to discern what exactly failed out of multiple asserts, all the assert methods I can think of have overloads with an extra message parameter - use this wisely to provide clear failure messages.


答:
I would prefer the two method approach. When one dies, you know specifically why it died and can fix it quicker. You don't have to test as much if requirements change part of the attributes.

That said, it's not the worst thing in the world to bundle some trivial checks like these into a 'does the car get built properly?' test.

Tests exist for your benefit, so do what benefits you the most. If the tiny tests are so annoying that they don't get written, that's way worse than the minor issue of bundling them.

Title: Is this method of writing Unit Tests correct?

Body:
I have created a small C# project to help me learn how to write good unit tests. I know that one important rule of unit testing is to test the smallest 'unit' of code possible so that if it fails you know exactly what part of the code needs to fixed. I need help with the following before I continue to implement more unit tests for the project:

If I have a Car class, for example, that creates a new Car object which has various attributes that are calculated when its' constructor method is called, would the two following tests be considered as overkill? Should there be one test that tests all calculated attributes of the Car object instead?

```<code>    [Test]
    public void CarEngineCalculatedValue()
    {
        BusinessObjects.Car car= new BusinessObjects.Car();
        Assert.GreaterOrEqual(car.Engine, 1);
    }

    [Test]
    public void CarNameCalculatedValue()
    {
        BusinessObjects.Car car= new BusinessObjects.Car();
        Assert.IsNotNull(car.Name);
    }
</code>```

Should I have the above two test methods to test these things or should I have one test method that asserts the Car object has first been created and then test these things in the same test method?


答:
Tabs vs Spaces!
I get crazy updates when one of my colleagues accidentally commits a lot of tabs to spaces shift into the repository</p>

Title: What should be in a coding standard?

Body:
What should be in a good (read:useful) coding standard?

Things the code should have.

Things the code shouldn't have.

Should the coding standard include definitions of things the language, compiler, or code formatter enforces?

What about metrics like cyclomatic complexity, lines per file, etc?


答:
Others already stated that global variables are not the solution. Here are some hints for managing local variables:

Some people declare their variables at the latest possible line (right before using them the first time). Others declare them all at the top of the function body (which is more compatible with very old standards). Either is fine, but choose one style and stick with it throughout a program.

If you find that you need many local variables in one function, it's a sign that you should split this function up. How many variables are too many? I'd say that more than 5 are uncomfortable. More than 10 unforgivable.

If you pass many arguments (more than 4) to a function, that's also a bad sign. Often, this can be solved by splitting the function into two or more smaller functions. Sometimes, you can aggregate the arguments into a struct and pass this around.

Properly name your functions and variables! I cannot emphasize this enough. Do not use names such as hlwrld or ac. Use helloWorld and accumulator. If you feel that those take too long to write, don't worry. You'll get faster at typing. And even if you don't, the time you save on debugging far outweighs the additional time for typing.


问:
Advantages and disadvantages to using XAML/C# or HTML5/JavaScipt for Metro apps?
I was just wondering if there are any major advantages or disadvantages to using either XAML/C# or HTML5/JavaScript for Metro Apps.</p>

答:
Metro Apps built using the HTML5/JS APIs will probably be classified as "simpler", compared to their C#/XAML counterparts. While the former will certainly be capable of creating functional, well designed apps, there will undoubtedly be a limit to the capabilities of an app built in HTML5. On the flip side, while C# might be more capable, it's also more complicated. An HTML5 app will be very easy to design and maintain, comparatively.

At least, that's my best estimated guess. I don't have experience developing Win8 apps (yet).


问:
What does it mean for SVN "to pollute the local source tree"?
I'm reading "Professional Team Foundation Server 2010" by Wrox, and in an advantages/disadvantages list, the said:

"Like CVS, SVN makes use of .svn directories inside the source folders to store state of the local working copy, and to allow synchronization with the server. However, it can have the affect of polluting the local source tree, and can cause performance issues wiht very large projects or files."

What does the bit about pollution mean? I've used SVN for C# & ASP.NET projects for a long time and haven't encountered any problems.  What probably does this quote think I should have been watching out for?

答:
"Polluting the source tree" is the term they're using to mean that SVN places hidden directories (.svn directories) throughout your source code.  The .svn directories contain metadata regarding your checked-out source code.  Traditionally, there has been a one-to-one correspondence between a directory in your source code and a corresponding .svn directory.  Therefore, bigger source code, more .svn directories.

Actually, SVN 1.7 drastically changes (for the better) how this process works.  Now, there is only one .svn directory for your entire working copy.  I don't think this "polluting" is a fair criticism any longer.

OwnerDisplayName: asd

OwnerDisplayName: William Leara