问:
Best practice Java - String array constant and indexing it
For string constants its usual to use a class with final String values. But whats the best practice for storing string array. I want to store different categories in a constant array and everytime a category has been selected, I want to know which category it belongs to and process based on that.

Addition : To make it more clear, I have a categories A,B,C,D,E which is a constant array. Whenever a user clicks one of the items(button will have those texts) I should know which item was clicked and do processing on that.

I can define an enum(say cat) and everytime do

```<code>if clickedItem == cat.A
 ....
else if clickedItem = cat.B
 ....
else if
 ....
</code>```

or even register listeners for each item seperately.

But I wanted to know the best practice for doing handling these kind of problems.

答:
Your description is quite vague, so maybe I got this wrong, but it sounds as you could use a Map<String,String> storing your category relationships. E.g. if you have

```<code>class Foo {
   final static String[] cat1 = {"val1_1","val1_2","val1_3"};
   final static String[] cat2 = {"val2_1","val2_2"};
}
</code>```

I would write:

```<code>class Foo {
  final static Map<String, String> map = new HashMap<String,String>();
  {
     map.put("val1_1","cat1");
     map.put("val1_2","cat1");
     map.put("val1_3","cat1");
     map.put("val2_1","cat2");
     map.put("val2_2","cat2");
  }
}
</code>```

Then getting the category is as easy as calling Foo.map.get("val1_1");. Of course you should be a little bit more clever than me filling when filling the map (e.g. from a file or so). If you are concerned with changes of the map, wrap it using Collections.unmodifiableMap.

Body:
Your description is quite vague, so maybe I got this wrong, but it sounds as you could use a Map<String,String> storing your category relationships. E.g. if you have

class Foo {
   final static String[] cat1 = {"val1_1","val1_2","val1_3"};
   final static String[] cat2 = {"val2_1","val2_2"};
}

I would write:

class Foo {
  final static Map<String, String> map = new HashMap<String,String>();
  {
     map.put("val1_1","cat1");
     map.put("val1_2","cat1");
     map.put("val1_3","cat1");
     map.put("val2_1","cat2");
     map.put("val2_2","cat2");
  }
}

Then getting the category is as easy as calling Foo.map.get("val1_1");. Of course you should be a little bit more clever than me filling when filling the map (e.g. from a file or so). If you are concerned with changes of the map, wrap it using Collections.unmodifiableMap.


问:
How to do thread management in C++?
We use pthread for thread management in C based systems. pthread is in general compilable by C++ compiler (like g++). However, what are the better ways of abstractions for threads in C++?

Also, for making any system to be working in a multi-threaded system, it is also important to make thread safe. What are the standard libraries that requires alternative (installs) to be thread safe or are they unsafe for multi-threaded environments?

Is smart pointers, templates require special measures to make it safe?

What are the best practices for the thread managements in C++?

答: In addition to what Jan Hudec wrote, if you want to use even higher level of abstraction (which can be a good idea) take a look at Intel Threading Building Blocks. Microsoft has Concurrency Runtime which is also excellent but MS specific.</p>

ContentLicense: CC BY-SA 3.0

Title: How to do thread management in C++?


问:
Can anyone help solve this complex algorithmic problem?
I got this question in an interview and I was not able to solve it.

You have a circular road, with N number of gas stations.

You know the amount of gas that each station has.

You know the amount of gas you need to GO from one station to the next one.

Your car starts with 0.

You can only drive clockwise.

The question is: Create an algorithm, to know from which gas station you must start driving so that you complete a full circle.

As an exercise to me, I would translate the algorithm to C#.

答:
Below is a description of how I think it could work. I can't claim that this is the only solution. I did not thoroughly test this so I leave this to you to verify.

In fact I think that it is too difficult to come up with during an interview.

The illustration attached shows the general idea. The variable x represents the current node being examined.

Use this formula if you for the first node.

Use this formula for nodes x=2,...,N

each node has amount of gas g(x) and the distance from node x to next node is given by d(x,x+1)

The R.H.S of the above equation should be the distance between the last two nodes in a route.

You start by generating a permutation of valid routes - Example:

route 1: A, B, C, D, A

route 2: B, C, D, A, B

route 3: C, D, A, B, C

route 4: D, A, B, C, D

The idea is that for each route,  at any node x of a given route, you need to calculate whether you can travel to the next node or not. This is determined as follows:

[Step 0] See how much gas you have so far + the max gas you can use from current station
if the above amount allows you to travel to the next station, then add this node to your route.

[Step 1] if the above amount is not enough, then the current start point is bad, try another route.

Now, to calculate how much gas you have at a node x, assume that for each unit of gas you consume, you travel 1 unit of distance, do this:

Sum all the gas filled from each gas stop (g1+g2+...+g(x-1)) - Sum all the distances traveled (d1+d2+...+d(x-1)) + Add to the above two sums the gas at this station (g(x))

Example1 - Using the provided data:

route 1, A,B,C,D

Calculating B(1):

g(1)=4

d(1,2)=5

B(1) = false. This means choosing the route A,B,C,D is not good since if you start at A, you will not have enough gas to go to B.

Example 2:

route 2, B,C,D,A

Calculating B(1):

g(1)=48

d(1,2)=45

g(1) <= d(1,2) is false, so B(1)=false that means starting at B is working so far. Continue to examine the situation at the next node (C)

g(2)=50

d(2,3)=44

g(1)-d(1,2) = 48-45

now

50 + (48-45) <= (d(2,3)=44) is false, so B(2) is false, this means that starting at B and getting to C is working so far. Continue the tests to see the status at next node (D)


答:
I much prefer using Enums to store system wide string constants, makes it easy to create additional functionality and I think it is generally accepted best practice.

```<code>public enum Cat {
     A() {
          @Override public void execute() {
               System.out.println("A clicked");
          }
     },
     B() {
          @Override public void execute() {
               System.out.println("B Clicked");
          }
     };
     //template method
     public abstract void execute();
}
</code>```

then you can call it like so :

```<code>String clickedItem = "A";
Cat.valueOf(clickedItem).execute(); //will print A is clicked
</code>```

or you could also the Command pattern without enums....

```<code>public interface Cat {
     void do();
}

public class CatA() implements Cat {
     void do() {//put your code here}
}
public class CatB() implements Cat {
     void do() {//put your other code here}
}
</code>```

then build a Map object and populate it with Cat instances:

```<code>catMap.put("A", new CatA());
catMap.put("B", new CatB());
</code>```

then you can replace your if/else if chain with:

```<code>catMap.get(clickedItem).do();
</code>```

Title: Best practice Java - String array constant and indexing it

Body:
For string constants its usual to use a class with final String values. But whats the best practice for storing string array. I want to store different categories in a constant array and everytime a category has been selected, I want to know which category it belongs to and process based on that.

Addition : To make it more clear, I have a categories A,B,C,D,E which is a constant array. Whenever a user clicks one of the items(button will have those texts) I should know which item was clicked and do processing on that.

I can define an enum(say cat) and everytime do

```<code>if clickedItem == cat.A
 ....
else if clickedItem = cat.B
 ....
else if
 ....
</code>```

or even register listeners for each item seperately.

But I wanted to know the best practice for doing handling these kind of problems.

Body:
I much prefer using Enums to store system wide string constants, makes it easy to create additional functionality and I think it is generally accepted best practice.

public enum Cat {
     A() {
          @Override public void execute() {
               System.out.println("A clicked");
          }
     },
     B() {
          @Override public void execute() {
               System.out.println("B Clicked");
          }
     };
     //template method
     public abstract void execute();
}

then you can call it like so :

String clickedItem = "A";
Cat.valueOf(clickedItem).execute(); //will print A is clicked

or you could also the Command pattern without enums....

public interface Cat {
     void do();
}

public class CatA() implements Cat {
     void do() {//put your code here}
}
public class CatB() implements Cat {
     void do() {//put your other code here}
}

then build a Map object and populate it with Cat instances:

catMap.put("A", new CatA());
catMap.put("B", new CatB());

then you can replace your if/else if chain with:

catMap.get(clickedItem).do();


问:
If you had to go back and re-learn your skill set, how would you do it?
My younger brother is looking to start programming. He's 14, and technically-inclined, but no real experience programming. He's looking to me for guidance, and I don't feel as if my experience is enough, so I figured I'd ask here.

He's more interested in web programming, but also has an interest in desktop/mobile/server applications.

What would be a good learning path for him to take? I'm going to buy him a bunch of books for Christmas to get him started; the question is, what should he learn, and in which order?

The way I see it, he needs to learn theory and code. I'd like to start him off with Python or Ruby or PHP. If he wants to get in to web, he's also going to need to learn HTML, CSS, Javascript, etc.

Out of those three domains (Languages, Theory, Markup/Etc.), what is the best order do you think to learn in? Also, am I missing anything?

Thanks!

答:
I'd like to start him off with Python or Ruby or PHP. If he wants to get in to web, he's also going to need to learn HTML, CSS, Javascript, etc.

This seems reasonable. Impart some basic skills and help him flesh out an idea for a challenging, project that he will remain interested in.

His first experiences don't need to be perfect, in fact it will help if he makes a ton of mistakes early. You just want to ensure that he remains interested in expanding his knowledge. When he hits his limitations, he will be begging for assistance and you can point him in the right direction if he hasn't already branched out to reference material.

ContentLicense: CC BY-SA 2.5


问:
What are the benefits of archiving?
I always see sites that only keeps fresh content on the home or subsections, and the rest of the content is kept in a separate section called 'archive'.

Recently I have also heard that NoSQL DB's like MongoDB are good for archiving (which makes me think this is related to performance)

So why do sites archive their content? What's the benefit over say, a simple paginator through which you could reach all the content?

Is archiving done for performance? Or SEO? Or just user experience?

答: "NoSQL" is actually a pretty broad category, so the designation doesn't mean much. And no, those DBs aren't any better at archiving old content than relational DBs. You should just keep the old content in the same data store that you're using for new content - no need to complicate things.</p>

Title: What are the benefits of archiving?


问:
What traits do the best testers you've worked with have in common?
Tester and blogger Lanette Creamer recently posted this question on Twitter:

If you are a professional software developer who works with testers, think of the best testers you know. What traits do they have in common?

I thought it would make an excellent question for here.

My thoughts are:

They want to remove ambiguity from requirements even if it means asking awkward questions.

They create new features by seeing the way software "should" work, rather than just how it's documented.

They demonstrate honesty and integrity and encourage but not demand it from those around them. In other words, they model behavior.

What are the traits of the best testers you've worked with?

答: Some of the best testers I've worked with really understand how the users are going to use the software.  They understand what business function the software is supposed to play and how that software will effect the user's role/job/function.  It makes for a successful project when the tester has as much knowledge of the business as the developer and the business owner.</p>


问:
Be liberal in what you accept... or not?
[Disclaimer: this question is subjective, but I would prefer getting answers backed by facts and/or reflexions]

I think everyone knows about the Robustness Principle, usually summed up by Postel's Law:

Be conservative in what you send; be liberal in what you accept.

I would agree that for the design of a widespread communication protocol this may make sense (with the goal of allowing easy extension), however I have always thought that its application to HTML / CSS was a total failure, each browser implementing its own silent tweak detection / behavior, making it near impossible to obtain a consistent rendering across multiple browsers.

I do notice though that there the RFC of the TCP protocol deems "Silent Failure" acceptable unless otherwise specified... which is an interesting behavior, to say the least.

There are other examples of the application of this principle throughout the software trade that regularly pop up because they have bitten developpers, from the top off my head:

Javascript semi-colon insertion

C (silent) builtin conversions (which would not be so bad if it did not truncated...)

and there are tools to help implement "smart" behavior:

name matching phonetic algorithms (Double Metaphone)

string distances algorithms (Levenshtein distance)

However I find that this approach, while it may be helpful when dealing with non-technical users or to help users in the process of error recovery, has some drawbacks when applied to the design of library/classes interface:

it is somewhat subjective whether the algorithm guesses "right", and thus it may go against the Principle of Least Astonishment

it makes the implementation more difficult, thus more chances to introduce bugs (violation of YAGNI ?)

it makes the behavior more susceptible to change, as any modification of the "guess" routine may break old programs, nearly excluding refactoring possibilities... from the start!

And this is what led me to the following question:

When designing an interface (library, class, message), do you lean toward the robustness principle or not ?

I myself tend to be quite strict, using extensive input validation on my interfaces, and I was wondering if I was perhaps too strict.

答:
I divide interfaces into several groups (add more if you like):

those that are under your control should be strict (classes typically)

library APIs, that should be also on strict side, but extra validation is advised

public interfaces that must handle every kind of abuse that comes in (typically protocols, user inputs, etc). Here robustness on input really pays off, you can't expect everyone is going to fix their stuff. And remember for user it will be your fault if the application doesn't work, not the party who sent some ill-formatted crap.

Output must always be strict.


答: Get him a book on Test Driven Development. It will make solid unit tests second nature to him. I wish I learded having tests as the core of my programming from square one. </p>

Title: If you had to go back and re-learn your skill set, how would you do it?

Body:
My younger brother is looking to start programming. He's 14, and technically-inclined, but no real experience programming. He's looking to me for guidance, and I don't feel as if my experience is enough, so I figured I'd ask here.

He's more interested in web programming, but also has an interest in desktop/mobile/server applications.

What would be a good learning path for him to take? I'm going to buy him a bunch of books for Christmas to get him started; the question is, what should he learn, and in which order?

The way I see it, he needs to learn theory and code. I'd like to start him off with Python or Ruby or PHP. If he wants to get in to web, he's also going to need to learn HTML, CSS, Javascript, etc.

Out of those three domains (Languages, Theory, Markup/Etc.), what is the best order do you think to learn in? Also, am I missing anything?

Thanks!


问:
Is there a language or design pattern that allows the *removal* of object behavior or properties in a class hierarchy?
A well-known shortcoming of traditional class hierarchies is that they are bad when it comes to modeling the real world. As an example, trying to represent animals' species with classes. There are actually several problems when doing that, but one that I never saw a solution to is when a sub-class "loses" a behavior or property that was defined in a super-class, like a penguin not being able to fly (there are probably better examples, but that's the first one that comes to my mind).

On the one hand, you don't want to define, for every property and behavior, some flag that specifies if it is at all present, and check it every time before accessing that behavior or property. You would just like to say that birds can fly, simply and clearly, in the Bird class. But then it would be nice if one could define "exceptions" afterward, without having to use some horrible hacks everywhere. This often happens when a system has been productive for a while. You suddenly find an "exception" that doesn't fit in the original design at all, and you don't want to change a large portion of your code to accommodate it.

So, are there some language or design patterns that can cleanly handle this problem, without requiring major changes to the "super-class", and all the code that uses it? Even if a solution only handles a specific case, several solutions might together form a complete strategy.

After thinking more, I realize I forgot about the Liskov Substitution Principle. That is why you can't do it. Assuming you define "traits/interfaces" for all major "feature groups", you can freely implement traits in different branches of the hierarchy, like the Flying trait could be implemented by Birds, and some special kind of squirrels and fish.

So my question could amount to "How could I un-implement a trait?" If your super-class is a Java Serializable, you have to be one too, even if there is no way for you to serialize your state, for example if you contained a "Socket".

One way to do it is to always define all your traits in pairs from the start: Flying and NotFlying (which would throw UnsupportedOperationException, if not checked against). The Not-trait would not define any new interface, and could be simply checked for. Sounds like a "cheap" solution, in particular if used from the start.

答:
The real problem with the fly() example is that the input and the output of the operation is not properly defined. What is required for a bird to fly? And what happens after flying succeeds? The parameter types and return types for the fly() function must have that information. Otherwise your design depends on random side effects and anything can happen. The anything part is what causes the whole problem, the interface is not properly defined and all kinds of implementation is allowed.

So, instead of this:

```<code>class Bird {
public:
   virtual void fly()=0;
};
</code>```

You should have something like this:

```<code>   class Bird {
   public:
      virtual float fly(float x) const=0;
   };
</code>```

Now it explicitly defines the limits of the functionality -- your flying behaviour has only single float to decide -- the distance from the ground, when given the position. Now the whole problem automatically solves itself. A Bird that cannot fly just returns 0.0 from that function, it never leaves the ground. It is correct behaviour for that, and once that one float is decided, you know you have fully implemented the interface.

Real behaviour can be difficult to encode to the types, but that's the only way to specify your interfaces properly.

Edit: I want to clarify one aspect. This float->float version of fly() function is important also because it defines a path. This version means that the one bird cannot magically duplicate itself while it's flying. This is why the parameter is single float - it's the position in the path which the bird takes. If you want more complex paths, then Point2d posinpath(float x); which uses the same x as the fly() function.

Body:
The real problem with the fly() example is that the input and the output of the operation is not properly defined. What is required for a bird to fly? And what happens after flying succeeds? The parameter types and return types for the fly() function must have that information. Otherwise your design depends on random side effects and anything can happen. The anything part is what causes the whole problem, the interface is not properly defined and all kinds of implementation is allowed.

So, instead of this:

class Bird {
public:
   virtual void fly()=0;
};

You should have something like this:

   class Bird {
   public:
      virtual float fly(float x) const=0;
   };

Now it explicitly defines the limits of the functionality -- your flying behaviour has only single float to decide -- the distance from the ground, when given the position. Now the whole problem automatically solves itself. A Bird that cannot fly just returns 0.0 from that function, it never leaves the ground. It is correct behaviour for that, and once that one float is decided, you know you have fully implemented the interface.

Real behaviour can be difficult to encode to the types, but that's the only way to specify your interfaces properly.

Edit: I want to clarify one aspect. This float->float version of fly() function is important also because it defines a path. This version means that the one bird cannot magically duplicate itself while it's flying. This is why the parameter is single float - it's the position in the path which the bird takes. If you want more complex paths, then Point2d posinpath(float x); which uses the same x as the fly() function.


问:
Are there any companies using BDD in a .NET environment?
I've seen BDD in action (in this case using SpecFlow and Selenium in a .NET environment) for a small test project. I was very impressed - mainly due to the fact that the language used to specify the acceptance tests meant they engaged with the product owner much more easily.

I'm now keen to bring this into my current organisation. However I'm asked 'who else uses this?' and 'show me some case-studies'.

Unfortunately I cannot find any 'big names' (or even 'small names' for that matter!) of companies who are actively using BDD.

I have two questions really:

Is BDD adopted by companies out there? Who are they?

How can BDD be implemented in an agile .NET environment and are there any significant drawbacks to doing it?

答:
I've used BDD extensively at many big clients, and seen it used in even more. If your organisation is hesitant about adopting the automation side, you can still focus on having the conversations between testers, developers and business people - this has really helped in a number of places.

At one .NET client we started automating Fitnesse.NET backed by FitSharp, but moved away from it when we realised that everyone who was interested in reading the automated scenarios was technical enough to read code. We were using WPF, so I wrote an automation tool to help us, and mirrored some of the things we were doing in a toy application. You can see the scenarios I wrote here. The way in which I've done this is really similar to what we were doing on the client site. I've also heard good things about SpecFlow, so either way forward should work.

As well as catching the occasional bug, talking through the scenarios really helped us understand what it was we were trying to achieve before we started coding, and we found many edge-cases as a result of the discussions. Every single project I've seen take up BDD has found benefit in it, with the one exception of a project which was only started because the sponsor wanted to use up his budget so he could be sure of getting it again the next year (the transparency around business value in BDD really annoys people who are gaming the system with things like this).

I have also put together a page on BDD which could help anyone who's new to it.

Lastly, you might want to check out Dan North's talk on selling BDD to the business.

OwnerDisplayName: Nick


答:
No, most companies aren't adopting BDD. Here's why:

In theory, BDD has some merit.

In practice, especially with a web application, BDD can require more effort than it's worth.

In my experience:

Creating BDD grammars is, at best, cumbersome.

Mocking HttpContext makes BDD more trouble than it's worth.

I'll allow that a screencast like this one, could make someone excited about BDD.

Unfortunately, the vast majority of real applications are never this straightforward.

Technical debt, often accumulated during schedule crunches, clutter most applications to a point where they aren't amendable to BDD.

Title: Are there any companies using BDD in a .NET environment?

Body:
I've seen BDD in action (in this case using SpecFlow and Selenium in a .NET environment) for a small test project. I was very impressed - mainly due to the fact that the language used to specify the acceptance tests meant they engaged with the product owner much more easily.

I'm now keen to bring this into my current organisation. However I'm asked 'who else uses this?' and 'show me some case-studies'.

Unfortunately I cannot find any 'big names' (or even 'small names' for that matter!) of companies who are actively using BDD.

I have two questions really:

Is BDD adopted by companies out there? Who are they?

How can BDD be implemented in an agile .NET environment and are there any significant drawbacks to doing it?


问:
What are the advantages of using bitwise operations?
Following reading the latest CodeProject newsletter, I came across this article on bitwise operations.  It makes for interesting reading, and I can certainly see the benefit of checking if an integer is even or odd, but testing if the n-th bit is set?  What can possibly be the advantages of this?</p>

答:
Bitwise operations are also used frequently in video and audio codecs, for the same reason as in embedded electronics; being able to pack five flags and an eleven bit timer into half an int is very useful when you want to make a super-efficient video codec.

In fact, MPEG 4 even uses exponential Golomb encoding for variable-bit-length fields. A value that was 17 or 19 bits wide last packet might be only three or five bits wide this packet - and you'd figure all that out with bitwise operations.


答:
(Update: now allows a gas tank size maximum)

You can solve this in linear time as follows:

```<code>void FindStartingPoint(int[] gasOnStation, int[] gasDrivingCosts, int gasTankSize)
{
  // Assume gasOnStation.length == gasDrivingCosts.length
  int n = gasOnStation.length;

  // Make a round, without actually caring how much gas we have.
  int minI = 0;
  int minEndValue = 0;
  int gasValue = 0;
  for (int i = 0; i < n; i++)
  {
    if (gasValue < minEndValue)
    {
      minI = i;
      minEndValue = gasValue;
    }
    gasValue = gasValue + gasOnStation[i] - gasDrivingCosts[i];
  }

  if (gasValue < 0)
  {
    Console.WriteLine("Instance does not have a solution: not enough fuel to make a round.");
  }
  else
  {
    // Try a round.
    int gas = DoLeg(0, minI, gasTankSize);
    if (gas < 0)
    {
      Console.WriteLine("Instance does not have a solution: our tank size is holding us back.");
      return;
    }
    for (int i = (minI + 1) % n; i != minI; i = (i + 1) % n)
    {
      gas = DoLeg(gas, i, gasTankSize);

      if (gas < 0)
      {
        Console.WriteLine("Instance does not have a solution: our tank size is holding us back.");
        return;
      }
    }
    Console.WriteLine("Start at station: " + minI);
  }
}
int DoLeg(int gas, int i, int gasTankSize)
{
  gas += gasOnStation[i];
  if (gas > gasTankSize) gas = gasTankSize;
  gas -= gasDrivingCosts[i];
  return gas;
}
</code>```

First, we look at the case where we don't have a gas tank with a maximum.

Essentially, in the first for-loop, we just drive the circle around, not caring if our fuel tank has negative fuel or not. The point of this is that no matter where you start, the difference between how much there is in your fuel tank at the start (0) and at the end is the same.

Therefore, if we end up with less fuel than we started (so less than 0), this will happen no matter where we start, and so we can't go a full circle.

If we end up with at least as much fuel as we started after going a full circle, then we search for the moment our fuel tank was at its lowest point (which is always just as we get to a gas station). If we start at this point, we will never end up with less fuel than at this point (because it is the lowest point and because we don't lose fuel if we drive a circle).

Therefore, this point is a valid solution, and in particular, there always is such a point.

Now we'll look at the version where our gas tank can hold only so much gas.

Suppose our initial test (described above) we found out it is not impossible to go the entire circle. Suppose that we start at gas station i, we tank at gas station j, but our gas tank ends up being full, so we miss out on some extra gas the station has available. Then, before we get to station k, we end up not having enough fuel, because of the gas we missed out on.

We claim that in this scenario, this will end up happening no matter where you start. Suppose we start at station l.

If l is between j and k, then we either stop (long) before we can get to station k because we started at a bad station, or we'll always have at most the amount of fuel that we had when we started at i when we try to get to k, because we passed through the same stations (and our tank was full when we passed j). Either case is bad.

If l is not between j and k, then we either stop (long) before we get to j, or we arrive at j with at most a full tank, which means that we won't make it to k either. Either case is bad.

This means that if we make a round starting at a lowest point just like in the case with the infinitely large gas tank, then we either succeed, or we fail because our gas tank was too small, but that means that we will fail no matter which station we pick first, which means that the instance has no solution.

Title: Can anyone help solve this complex algorithmic problem?

Body:
I got this question in an interview and I was not able to solve it.

You have a circular road, with N number of gas stations.

You know the amount of gas that each station has.

You know the amount of gas you need to GO from one station to the next one.

Your car starts with 0.

You can only drive clockwise.

The question is: Create an algorithm, to know from which gas station you must start driving so that you complete a full circle.

As an exercise to me, I would translate the algorithm to C#.

Body:
(Update: now allows a gas tank size maximum)

You can solve this in linear time as follows:

void FindStartingPoint(int[] gasOnStation, int[] gasDrivingCosts, int gasTankSize)
{
  // Assume gasOnStation.length == gasDrivingCosts.length
  int n = gasOnStation.length;

  // Make a round, without actually caring how much gas we have.
  int minI = 0;
  int minEndValue = 0;
  int gasValue = 0;
  for (int i = 0; i < n; i++)
  {
    if (gasValue < minEndValue)
    {
      minI = i;
      minEndValue = gasValue;
    }
    gasValue = gasValue + gasOnStation[i] - gasDrivingCosts[i];
  }

  if (gasValue < 0)
  {
    Console.WriteLine("Instance does not have a solution: not enough fuel to make a round.");
  }
  else
  {
    // Try a round.
    int gas = DoLeg(0, minI, gasTankSize);
    if (gas < 0)
    {
      Console.WriteLine("Instance does not have a solution: our tank size is holding us back.");
      return;
    }
    for (int i = (minI + 1) % n; i != minI; i = (i + 1) % n)
    {
      gas = DoLeg(gas, i, gasTankSize);

      if (gas < 0)
      {
        Console.WriteLine("Instance does not have a solution: our tank size is holding us back.");
        return;
      }
    }
    Console.WriteLine("Start at station: " + minI);
  }
}
int DoLeg(int gas, int i, int gasTankSize)
{
  gas += gasOnStation[i];
  if (gas > gasTankSize) gas = gasTankSize;
  gas -= gasDrivingCosts[i];
  return gas;
}

First, we look at the case where we don't have a gas tank with a maximum.

Essentially, in the first for-loop, we just drive the circle around, not caring if our fuel tank has negative fuel or not. The point of this is that no matter where you start, the difference between how much there is in your fuel tank at the start (0) and at the end is the same.

Therefore, if we end up with less fuel than we started (so less than 0), this will happen no matter where we start, and so we can't go a full circle.

If we end up with at least as much fuel as we started after going a full circle, then we search for the moment our fuel tank was at its lowest point (which is always just as we get to a gas station). If we start at this point, we will never end up with less fuel than at this point (because it is the lowest point and because we don't lose fuel if we drive a circle).

Therefore, this point is a valid solution, and in particular, there always is such a point.

Now we'll look at the version where our gas tank can hold only so much gas.

Suppose our initial test (described above) we found out it is not impossible to go the entire circle. Suppose that we start at gas station i, we tank at gas station j, but our gas tank ends up being full, so we miss out on some extra gas the station has available. Then, before we get to station k, we end up not having enough fuel, because of the gas we missed out on.

We claim that in this scenario, this will end up happening no matter where you start. Suppose we start at station l.

If l is between j and k, then we either stop (long) before we can get to station k because we started at a bad station, or we'll always have at most the amount of fuel that we had when we started at i when we try to get to k, because we passed through the same stations (and our tank was full when we passed j). Either case is bad.

If l is not between j and k, then we either stop (long) before we get to j, or we arrive at j with at most a full tank, which means that we won't make it to k either. Either case is bad.

This means that if we make a round starting at a lowest point just like in the case with the infinitely large gas tank, then we either succeed, or we fail because our gas tank was too small, but that means that we will fail no matter which station we pick first, which means that the instance has no solution.


问:
Should I keep separate client codebases and databases for a software-as-a-service application?
My question is about the architecture of my application. I have a Rails application where companies can administrate all things related to their clients. Companies would buy a subscription and their users can access the application online. Hopefully I will get multiple companies subscribing to my application/service. What should I do with my code and database?

Seperate app code base and database per company

One app code base but seperate database per company

One app code base and one database

The decision involves security (e.g. a user from company X should not see any data from company Y) performance (let's suppose it becomes successful, it should have a good performance) and scalability (again, if successful, it should have a good performance but also easy for me to handle all the companies, code changes, etc).

For the sake of maintainability, I tend to opt for the one code base, but for the database I really don't know. What do you think is the best option?

答:
Personally I would go for the third option. Rails also makes it pretty simple to 'sandbox' the data related to a certain user so that others cannot see it.
From a performance point of view having one database to handle all the data can cause queries to be slower but there are numerous ways of improving this.</p>


问:
Does HTML5 have a feature that enables a user to add an icon to the Apps screen when "installing", and if not, when are they planning to add it?
I know that the mobile bookmark bubble might sort of work for iOS, but it isn't going in the same section.  And for Android, bookmarking is really not going to cut it for a mobile HTML5 application install since users just don't think to go to their bookmarks and that bookmark process takes two or three steps.

To me this issue of getting the application (bookmark) installed pretty much makes the rest of the HTML 5 features aimed at mobile HTML much less useful.  I can't realistically expect users to prefer the bookmark install and launch process over regular apps, so I can realistically expect them to ignore my mobile HTML5 application and use a native app.

The groups behind mobile HTML 5 features do seem to be pushing for HTML 5 apps adoption with things like Application Cache etc.  To me it seems obvious that the bookmark bubble is not going to cut it.  Someone please tell me they have addressed this or at least are working on it?

答: I don't think they are planning to add it. This is more of an OS thing; in iOS, a bookmark can be saved within an application wrapper and launched from the Springboard. I assume Android will eventually adopt the same technique -- or it won't, in which case you'll have to develop a workaround on your own.</p>


答:
True story

The simplest reason to separate newer content from older content is that your database is getting to big. A few years ago I was involved with building a huge financial application that was based on an pre-existing database. It kept a variety of fiscal data, and it already had several years worth of data in it, when I first became involved with the project. Having a single database store years of data only makes sense when there you actually need all this data, at any given time. The rest of the team said that was the case, so I didn't think much of it.

A few weeks into the team I realised that the reality was a little bit different. Our users only needed to access the current fiscal year's data, except:

When producing yearly reports, something that happened once a year

When producing three year reports, something that happened once every three years

We decided to split the database into different databases, per year. It wasn't an easy decision but it worked: The current fiscal year database had lightning fast responses, as it was only scanning through a very small subset of the whole data. The yearly reports where also generated on the fly, for the same reason. The three year reports were a little bit slower to generate than before and it took a lot of creativity to combine three archives, but  that was a very small disadvantage of the process.

So our database was split into small archive databases, and everyone was happy. (Not really, lot of rough edges and of course this is an oversimplified version of the story, but overall the decision to archive was a good one).

Heterogeneous data

Another reason to archive is when you have lack of data homogeneity over time. When the schema of the database changes, especially for huge databases, your best bet is a document-oriented database like MongoDB. Document-oriented databases have flexible schemas, which means that they don't care if you don't use the same fields to describe a record, hence you don't have empty fields as you would with a relational database.

And as Jeff O correctly notes in a comment to another answer, archived data by definition won't change, so you don't need to care about transactions and other relational functionality. (Added here, in case comment or answer goes AWOL)

Archiving on news oriented websites

News oriented websites with lots of data may opt in to archive their older content into a document-oriented database, because since they deal in news, their fresher content is a lot more valuable to them from a business point of view.

SEO & pagination

Lastly, it has nothing to do with SEO and / or pagination (Pagination will work regardless of where your content is stored). A bot will scan through your paginated content, following the pagination links like any other link. If you adopt a sensible URI schema for all your content, you have nothing to worry about. For example, imagine you have a blog with ten years of articles and you've decided to move all articles that are older than 2010-12-31 to a document storage archive.

Your homepage would probably have a list of newest articles, something like

```<code>http://example.com/articles/2011-11-1/title
http://example.com/articles/2011-10-30/title
http://example.com/articles/2011-10-20/title
</code>```

Going through the pages you finally stumble upon a page:

```<code>http://example.com/articles/2011-1-1/title
http://example.com/articles/2010-12-30/title
http://example.com/articles/2010-12-25/title
</code>```

Same URI schema, regardless of whether the article is stored on your current database or your archive database. All you have to do is a simple server side check when your visitor (human or bot) clicks on the 2010-12-30 article:

```<code>if(date <= 2010-12-31) {
    // get article information from archive
} else {
    // get article information from current database
}
</code>```

Now why some sites may choose to move archived content into a special archive section, is something that's answerable only by those who built them. There may be a few user experience factors involved, but that's off topic for Programmers, you can try inquiring the folks over at User Experience Stack Exchange.

Title: What are the benefits of archiving?

Body:
I always see sites that only keeps fresh content on the home or subsections, and the rest of the content is kept in a separate section called 'archive'.

Recently I have also heard that NoSQL DB's like MongoDB are good for archiving (which makes me think this is related to performance)

So why do sites archive their content? What's the benefit over say, a simple paginator through which you could reach all the content?

Is archiving done for performance? Or SEO? Or just user experience?

Body:
True story

The simplest reason to separate newer content from older content is that your database is getting to big. A few years ago I was involved with building a huge financial application that was based on an pre-existing database. It kept a variety of fiscal data, and it already had several years worth of data in it, when I first became involved with the project. Having a single database store years of data only makes sense when there you actually need all this data, at any given time. The rest of the team said that was the case, so I didn't think much of it.

A few weeks into the team I realised that the reality was a little bit different. Our users only needed to access the current fiscal year's data, except:

When producing yearly reports, something that happened once a year

When producing three year reports, something that happened once every three years

We decided to split the database into different databases, per year. It wasn't an easy decision but it worked: The current fiscal year database had lightning fast responses, as it was only scanning through a very small subset of the whole data. The yearly reports where also generated on the fly, for the same reason. The three year reports were a little bit slower to generate than before and it took a lot of creativity to combine three archives, but  that was a very small disadvantage of the process.

So our database was split into small archive databases, and everyone was happy. (Not really, lot of rough edges and of course this is an oversimplified version of the story, but overall the decision to archive was a good one).

Heterogeneous data

Another reason to archive is when you have lack of data homogeneity over time. When the schema of the database changes, especially for huge databases, your best bet is a document-oriented database like MongoDB. Document-oriented databases have flexible schemas, which means that they don't care if you don't use the same fields to describe a record, hence you don't have empty fields as you would with a relational database.

And as Jeff O correctly notes in a comment to another answer, archived data by definition won't change, so you don't need to care about transactions and other relational functionality. (Added here, in case comment or answer goes AWOL)

Archiving on news oriented websites

News oriented websites with lots of data may opt in to archive their older content into a document-oriented database, because since they deal in news, their fresher content is a lot more valuable to them from a business point of view.

SEO & pagination

Lastly, it has nothing to do with SEO and / or pagination (Pagination will work regardless of where your content is stored). A bot will scan through your paginated content, following the pagination links like any other link. If you adopt a sensible URI schema for all your content, you have nothing to worry about. For example, imagine you have a blog with ten years of articles and you've decided to move all articles that are older than 2010-12-31 to a document storage archive.

Your homepage would probably have a list of newest articles, something like

http://example.com/articles/2011-11-1/title
http://example.com/articles/2011-10-30/title
http://example.com/articles/2011-10-20/title

Going through the pages you finally stumble upon a page:

http://example.com/articles/2011-1-1/title
http://example.com/articles/2010-12-30/title
http://example.com/articles/2010-12-25/title

Same URI schema, regardless of whether the article is stored on your current database or your archive database. All you have to do is a simple server side check when your visitor (human or bot) clicks on the 2010-12-30 article:

if(date <= 2010-12-31) {
    // get article information from archive
} else {
    // get article information from current database
}

Now why some sites may choose to move archived content into a special archive section, is something that's answerable only by those who built them. There may be a few user experience factors involved, but that's off topic for Programmers, you can try inquiring the folks over at User Experience Stack Exchange.


问:
How can I learn to effectively write Pythonic code?
Doing a google search for "pythonic" reveals a wide range of interpretations.  The wikipedia page says:

A common neologism in the Python community is pythonic, which can have a wide range of meanings related to program style. To say that code is pythonic is to say that it uses Python idioms well, that it is natural or shows fluency in the language. Likewise, to say of an interface or language feature that it is pythonic is to say that it works well with Python idioms, that its use meshes well with the rest of the language.

It also discusses the term "unpythonic":

In contrast, a mark of unpythonic code is that it attempts to write C++ (or Lisp, Perl, or Java) code in Python—that is, provides a rough transcription rather than an idiomatic translation of forms from another language. The concept of pythonicity is tightly bound to Python's minimalist philosophy of readability and avoiding the "there's more than one way to do it" approach. Unreadable code or incomprehensible idioms are unpythonic.

What does the term "pythonic" mean?  How do I learn to effectively apply it in practice?

答: Pythonic is to code idiomatically in Python. It means using structures and formatting that work well for Python from a programming standpoint but also from a community reading standpoint. It's very much like how K&R set the standard for C programming style for a long time. This guide shows you have to code idiomatically in Python. PEP 8 is referenced in that guide so it's probably worth reading.</p>


答: Python is not Java might give you some useful advice. Can't say more without know what sort of issues you are running into, but it's very concrete advice for programmers coming from another language (in this case specifically java) background on how to do python differently.</p>

Title: How can I learn to effectively write Pythonic code?

Body:
Doing a google search for "pythonic" reveals a wide range of interpretations.  The wikipedia page says:

A common neologism in the Python community is pythonic, which can have a wide range of meanings related to program style. To say that code is pythonic is to say that it uses Python idioms well, that it is natural or shows fluency in the language. Likewise, to say of an interface or language feature that it is pythonic is to say that it works well with Python idioms, that its use meshes well with the rest of the language.

It also discusses the term "unpythonic":

In contrast, a mark of unpythonic code is that it attempts to write C++ (or Lisp, Perl, or Java) code in Python—that is, provides a rough transcription rather than an idiomatic translation of forms from another language. The concept of pythonicity is tightly bound to Python's minimalist philosophy of readability and avoiding the "there's more than one way to do it" approach. Unreadable code or incomprehensible idioms are unpythonic.

What does the term "pythonic" mean?  How do I learn to effectively apply it in practice?


答:
Writing "Pythonic" code IMHO is just making effective use of the (V)HLL features the language provides. As an ubiquitous example,

```<code>x, y = 7, 'fuhrer'
</code>```

That is very Pythonic. I remember when I started learning C# after months of only Python,

```<code>int x, y = 10, z;
</code>```

somehow confused me, but it took a minute for me to return to my C/C++ roots.

Another Pythonic way is using lambdas.

```<code>l = [1, 2, 3, 4, 5]
print(sorted(l, key=lambda x: -x))
</code>```

will actually print l sorted in descending order.

Then there is the very much used, but very less understood "duck typing" - If it walks and talks like a duck, you treat it as a duck. This is loosely related to interfaces in other OO languages.

Also using functional programming methods where applicable, such as the use of map and reduce are considered pythonic.

I saw an answer being posted as I was typing, and it contains a nice link.
PS: It's not that your knowledge of Python is limited. I can bet that Python was not your first language, and hence, (like most of us pythonistas) you'll have to learn to get "idiomatic" with the snake! Cheers!

Body:
Writing "Pythonic" code IMHO is just making effective use of the (V)HLL features the language provides. As an ubiquitous example,

x, y = 7, 'fuhrer'

That is very Pythonic. I remember when I started learning C# after months of only Python,

int x, y = 10, z;

somehow confused me, but it took a minute for me to return to my C/C++ roots.

Another Pythonic way is using lambdas.

l = [1, 2, 3, 4, 5]
print(sorted(l, key=lambda x: -x))

will actually print l sorted in descending order.

Then there is the very much used, but very less understood "duck typing" - If it walks and talks like a duck, you treat it as a duck. This is loosely related to interfaces in other OO languages.

Also using functional programming methods where applicable, such as the use of map and reduce are considered pythonic.

I saw an answer being posted as I was typing, and it contains a nice link.
PS: It's not that your knowledge of Python is limited. I can bet that Python was not your first language, and hence, (like most of us pythonistas) you'll have to learn to get "idiomatic" with the snake! Cheers!


答:
Updated

Depending on the iOS version, you need either 72*72 or 114*114 icons.
Also, you can specify the icon is precomposed (iOS just adds arounded corners) or not (it also adds a shine effect on top of it).

However Android (2.1+) can only handle precomposed icons.

So if you're looking for a one-code-fits-most, use this snipplet:

```<code><!-- For iPhone 4 with high-resolution Retina display -->
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="apple-touch-icon-114x114-precomposed.png">

<!-- For first-generation iPad -->
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="apple-touch-icon-72x72-precomposed.png">

<!-- For non-Retina iPhone, iPod Touch, and Android 2.1+ devices: -->
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">
</code>```

Android and iOS 4.1 use the last icon in that list, that's why the link without sizes ais at the end.

However, both iOS and Android will add the link only if the user chooses to create the link, there is no way to do it without user interaction currently, nor is there anything in HTML5 to introduce such a feature yet.

And if you're making web application, make sure to add this tag (the webpage will be opened fullscreen on iOS):

```<code><meta name="apple-mobile-web-app-capable" content="yes" />
</code>```

and furthemore, you can specify a loading screen for iOS:

```<code><!-- 320x460 for iPhone 3GS -->
<link rel="apple-touch-startup-image" media="(max-device-width: 480px) and not (-webkit-min-device-pixel-ratio: 2)" href="startup-iphone.png">

<!-- 640x920 for retina display -->
<link rel="apple-touch-startup-image" media="(max-device-width: 480px) and (-webkit-min-device-pixel-ratio: 2)" href="startup-iphone4.png">

<!-- iPad Portrait 768x1004 -->
<link rel="apple-touch-startup-image" media="(min-device-width: 768px) and (orientation: portrait)" href="startup-iPad-portrait.png">

<!-- iPad Landscape 1024x748 -->
<link rel="apple-touch-startup-image" media="(min-device-width: 768px) and (orientation: landscape)" href="startup-iPad-landscape.png">
</code>```

Title: Does HTML5 have a feature that enables a user to add an icon to the Apps screen when "installing", and if not, when are they planning to add it?

Body:
I know that the mobile bookmark bubble might sort of work for iOS, but it isn't going in the same section.  And for Android, bookmarking is really not going to cut it for a mobile HTML5 application install since users just don't think to go to their bookmarks and that bookmark process takes two or three steps.

To me this issue of getting the application (bookmark) installed pretty much makes the rest of the HTML 5 features aimed at mobile HTML much less useful.  I can't realistically expect users to prefer the bookmark install and launch process over regular apps, so I can realistically expect them to ignore my mobile HTML5 application and use a native app.

The groups behind mobile HTML 5 features do seem to be pushing for HTML 5 apps adoption with things like Application Cache etc.  To me it seems obvious that the bookmark bubble is not going to cut it.  Someone please tell me they have addressed this or at least are working on it?

Body:
Updated

Depending on the iOS version, you need either 72*72 or 114*114 icons.
Also, you can specify the icon is precomposed (iOS just adds arounded corners) or not (it also adds a shine effect on top of it).

However Android (2.1+) can only handle precomposed icons.

So if you're looking for a one-code-fits-most, use this snipplet:

<!-- For iPhone 4 with high-resolution Retina display -->
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="apple-touch-icon-114x114-precomposed.png">

<!-- For first-generation iPad -->
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="apple-touch-icon-72x72-precomposed.png">

<!-- For non-Retina iPhone, iPod Touch, and Android 2.1+ devices: -->
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

Android and iOS 4.1 use the last icon in that list, that's why the link without sizes ais at the end.

However, both iOS and Android will add the link only if the user chooses to create the link, there is no way to do it without user interaction currently, nor is there anything in HTML5 to introduce such a feature yet.

And if you're making web application, make sure to add this tag (the webpage will be opened fullscreen on iOS):

<meta name="apple-mobile-web-app-capable" content="yes" />

and furthemore, you can specify a loading screen for iOS:

<!-- 320x460 for iPhone 3GS -->
<link rel="apple-touch-startup-image" media="(max-device-width: 480px) and not (-webkit-min-device-pixel-ratio: 2)" href="startup-iphone.png">

<!-- 640x920 for retina display -->
<link rel="apple-touch-startup-image" media="(max-device-width: 480px) and (-webkit-min-device-pixel-ratio: 2)" href="startup-iphone4.png">

<!-- iPad Portrait 768x1004 -->
<link rel="apple-touch-startup-image" media="(min-device-width: 768px) and (orientation: portrait)" href="startup-iPad-portrait.png">

<!-- iPad Landscape 1024x748 -->
<link rel="apple-touch-startup-image" media="(min-device-width: 768px) and (orientation: landscape)" href="startup-iPad-landscape.png">


答:
I would recommend sticking to a single codebase as best you can unless there are major customizations required by clients that you don't think will be reusable for others. Keeping multiple codebases in sync can turn into a maintenance nightmare, which will only escalate as your client base grows.

As for the database, it's usually best to keep the number to a minimum, but there are a few cases where it makes sense to partition your client data in separate databases:

You have strict (i.e. healthcare or financial industry) requirements on client data confidentiality.

Database performance becomes a problem.

Summary: option 3

Title: Should I keep separate client codebases and databases for a software-as-a-service application?

Body:
My question is about the architecture of my application. I have a Rails application where companies can administrate all things related to their clients. Companies would buy a subscription and their users can access the application online. Hopefully I will get multiple companies subscribing to my application/service. What should I do with my code and database?

Seperate app code base and database per company

One app code base but seperate database per company

One app code base and one database

The decision involves security (e.g. a user from company X should not see any data from company Y) performance (let's suppose it becomes successful, it should have a good performance) and scalability (again, if successful, it should have a good performance but also easy for me to handle all the companies, code changes, etc).

For the sake of maintainability, I tend to opt for the one code base, but for the database I really don't know. What do you think is the best option?


答:
Personally, I would go with option #1 laced with lots of self-discipline until I had a very, very good understanding of the problem and what parts needed to be extensible on a per-client basis. Given you are starting off, you probably have some ideas as to what you want customizable, but your clients will want to customize things in ways you've never dream of. If you have a single application or a single codebase or both you'll then have to worry about how Client A's special needs impact Client B and vice versa. Having everyone in their own sandbox is a good way to be able to serve the customers, especially early-on when you really need to keep the few customer's you've got. Once the product matures a bit you will have a much better idea of where to build the extensibility points and how to make a single codebase that can serve most customers.

In terms of managing, it really isn't that hard with a bit of discipline. I'm not horribly familiar with ruby so I'm not sure what exact tools one would need to use, but with good scm practices and some automated deployment tools you can keep a handle on management while you are starting out. If you've got nightmares managing this codebase and all the separate apps then you've probably got a good problem to have. Alot better than figuring out how to customize a single monolithic codebase in most cases.


问:
Is there an alternative to the term "calling object"?
Let's suppose you've got a class defined (in pseudocode):

```<code>class Puppy {
    // ...
    string sound = "Rawr!";

    void bark() {
        print(sound);
    }
}
</code>```

And say, given a Puppy instance, you call it's bark() method:

```<code>int main() {
    Puppy p;
    p.bark();
}
</code>```

Notice how bark() uses the member variable sound. In many contexts, I've seen folks describe sound as the member variable of the "calling object."

My question is, what's a better term to use than "calling object"?

To me, the object is not doing any calling. We know that member functions are in a way just functions with an implicit this or self parameter.

I've come up with "receiving object" or "message recipient" which makes sense if you're down with the "messaging" paradigm.

Do any of you happy hackers have a term that you like to use?

I feel it should mean "the object upon which a method is called" and TOUWAMIC just doesn't cut it.

As for who the "caller" is, I would say that main instantiates a Puppy object and calls its bark() method.

答: I'd generally call p an instance of Puppy, not the calling object

ContentLicense: CC BY-SA 4.0


答:
Using the word object in the reference is redundant.

Perhaps caller and callee is simplistic enough. Referring to the actual object as an instance of type is also another approach as noted by Wyatt; instance of Puppy or if being succinct is the goal...instance.

Title: Is there an alternative to the term "calling object"?

Body:
Let's suppose you've got a class defined (in pseudocode):

```<code>class Puppy {
    // ...
    string sound = "Rawr!";

    void bark() {
        print(sound);
    }
}
</code>```

And say, given a Puppy instance, you call it's bark() method:

```<code>int main() {
    Puppy p;
    p.bark();
}
</code>```

Notice how bark() uses the member variable sound. In many contexts, I've seen folks describe sound as the member variable of the "calling object."

My question is, what's a better term to use than "calling object"?

To me, the object is not doing any calling. We know that member functions are in a way just functions with an implicit this or self parameter.

I've come up with "receiving object" or "message recipient" which makes sense if you're down with the "messaging" paradigm.

Do any of you happy hackers have a term that you like to use?

I feel it should mean "the object upon which a method is called" and TOUWAMIC just doesn't cut it.

As for who the "caller" is, I would say that main instantiates a Puppy object and calls its bark() method.


答:
I've found that a most people have their own interpretations of what being "Pythonic" really means. From Wikipedia:

A common neologism in the Python community is pythonic, which can have
a wide range of meanings related to program style. To say that code is
pythonic is to say that it uses Python idioms well, that it is natural
or shows fluency in the language. Likewise, to say of an interface or
language feature that it is pythonic is to say that it works well with
Python idioms, that its use meshes well with the rest of the language.

In contrast, a mark of unpythonic code is that it attempts to write
C++ (or Lisp, Perl, or Java) code in Python—that is, provides a rough
transcription rather than an idiomatic translation of forms from
another language. The concept of pythonicity is tightly bound to
Python's minimalist philosophy of readability and avoiding the
"there's more than one way to do it" approach. Unreadable code or
incomprehensible idioms are unpythonic.

I've found that more times than not, more "pythonic" examples are actually derived from people trying to be clever with Python idioms and (again, more times than not) rendering their code virtually unreadable (which is not Pythonic).

As long as you're sticking to Python's idioms and avoiding trying to use C++ (or other language) styles in Python, then you're being Pythonic.

As pointed out by WorldEngineer, PEP8 is a good standard to follow (and if you use VIM, there are plugins available for PEP8 linting).

Really though, at the end of the day, if your solution works and isn't absolutely horribly un-maintainable and slow, who cares? More times than not, your job is to get a task done, not write the most elegant, pythonic code possible.

Another side note (just my opinion, feel free to downvote because of it ;)): I've also found the Python community to be filled with a ton of ego (not that most communities aren't, it's just a little more prevalent in communities such as C and Python). So, combining the ego with misconstrued interpretations of being "pythonic" will tend to yield a whole lot of baseless negativity. Take what you read from others with a grain of salt. Stick to official standards and documentation and you'll be fine.


答:
Based on your comment in Wyatt's post:

Rather, how to describe p in the context of method calls.

I'd have to go with describing p in the context of method calls as being the "method's instance".

In object-oriented programming, a method is a subroutine (or procedure or function) associated with a class. [Wikipedia]

As such, when describing the inverse relationship, I would believe that "method's instance" would be correct your described context (but exchanging class for instance as we're describing the relationship to the instance, not the class definition itself).


问:
How many are too many interfaces on a class?
I would probably consider it a code smell or even an anti-pattern to have a class that implements 23 interfaces. If it is indeed an anti-pattern, what would you call it? Or is it simply just not following the Single responsibility principle?</p>

答:
The number of interfaces often grows when a generic object is used in different environments. In C# the variants of IComparable, IEqualityComparer and IComparer allow sorting in distinct setups, so you might end up implementing all of them, some of them maybe more than once since you can implement the generic strongly typed versions as well as the non-generic versions, additionally you can implement more than one of the generics.

Let's take an example scenario, let's say a webshop where you can buy credits with which you can buy something else (stock photo sites often use this scheme). You might have a class "Valuta" and a class "Credits" that inherit form the same base. Valuta has some nifty operator overloads and comparison routines that allow you to do calculations without worrying about the "Currency" property (adding pounds to dollars for example). Credits are allot simpler but have some other distinct behavior. Wanting to be able to compare these with each other, you could end up implementing IComparable as well as IComparable and the other variants of comparison interfaces on both (even though they use a common implementation whether it be in the base class or somewhere else).

When implementing serialization, ISerializable, IDeserializationCallback get implemented.
Then implementing undo-redo stacks: IClonable is added.
IsDirty functionality: IObservable, INotifyPropertyChanged.
Allowing users to edit the values using strings: IConvertable...
The list can go on and on...

In modern languages we see a different trend that helps separate these aspects and place them in their own classes, outside the core class. The outside class or aspect is then associated with the target class by using annotation (attributes). Often it is possible to make the outer aspect classes more or less generic.

The use of attributes (annotation) is subject to reflection. One drawback is minor (initial) performance loss. An (often emotional) drawback is that principles such as encapsulation need to be relaxed.

There are always other solutions, but for every nifty solution there is a tradeoff or a catch. For example, using an ORM solution might demand all properties to be declared virtual. Serialization solutions might demand default constructors on your classes. If you are utilizing dependency injection you might end up implementing 23 interfaces on a single class.

In my eyes, 23 interfaces does not have to be bad by definition. There might a well thought out scheme behind it, or some principle determination such as avoiding the use of reflection or extreme encapsulation beliefs.

Whenever switching a job, or having to build on an existing architecture. My advice is to first get fully acquainted, do not try to refactor everything too quickly. Listen to the original developer (if he's still there) and try to figure out the thoughts and ideas behind what you see. When asking questions, do so not for the sake of breaking it down, but to learn... Yes, everyone has their own golden hammers, but the more hammers you can collect the easier you will get along with fellow colleagues.


答:
I'd go with any of:

call target

method owner (although this doesn't really make sense if p is null, because then it hardly owns anything)

callee

Although in that very context, I'd go with p ;)


问:
Mission critical embedded language
Maybe the question sounds a bit strange, so I'll explain a the background a little bit.

Currently I'm working on a project at y university, which will be a complete on-board software for an satellite. The system is programmed in C++ on top of a real-time operating system. However, some subsystems like the attitude control system and the fault detection and a space simulation are currently only implemented in Matlab/Simulink, to prototype the algorithms efficiently. After their verification, they will be translated into c++.

The complete on-board software grew very complex, and only a handful people know the whole system. Furthermore, many of the students haven't program in C++ yet and the manual memory management of C++ makes it even more difficult to write mission critical software.

Of course the main system has to be implemented in C++, but I asked myself if it's maybe possible to use an embedded language to implement the subsystem which are currently written in Matlab. This embedded language should feature:

static/strong typing and compiler checks to minimize runtime errors

small memory usage, and relative fast runtime

attitude control algorithms are mainly numerical computations, so a good numeric support would be nice

maybe some sort of functional programming feature, matlab/simulink encourage you to use it too

I googled a bit, but only found Lua. It looks nice, but I would not use it in mission critical software. Have you ever encountered a situation like this, or do you know any language, which could satisfies the conditions?

EDIT: To clarify some things: embedded means it should be able to embed the language into the existing C++ environment. So no compiled languages like Ada or Haskell

答: You might be looking for Ada. You might have trouble finding someone outside of NASA who has written code in it though.</p>

Title: Mission critical embedded language


问:
How can I prevent a client from seeing my code written in an interpreted language?
I'm building a fairly complex interpreted program in Python. I've been working on most of this code for other purposes for a few months, and therefore don't want my client to be able to simply copy and try to sell it, as I think it's worth a fair amount.

The problem is that I need the script to run on a server that my client is paying for, so is there any way I can secure a particular folder on the machine from root access, or make it so only one particular use can access the directory? The OS is Ubuntu.

答: Licensing is the best answer here. That said, why does it have to run on their gear? If it is so critically important you might want to spring for a service and build some sort of service API around things so folks can't even see your intellectual property to steal it.</p>

OwnerDisplayName: James Eggers


答:
p is the receiver, recipient, target, callee, "the puppy," or just "p".

The object sending the message/calling the method is the sender or caller. Caller can also mean the function or method calling p.bark().

Sometimes the relationship between the objects is used instead because that's an easier way to identify the two, so one might be the parent and the other the child, or one might be the delegate and the other the delegator.


答:
I'll suggest Haskell as food for thought, even though it doesn't meet all your criteria:

Pros:

very good type system, lots of compiler checks -- it's extremely hard to get Haskell to even condescend to look at your program, much less compile it! :)

no manual memory management

pure functional programming language, full complement of FP features

Cons:

very few people know Haskell, and may be hard to learn

not similar to mainstream languages -- different idioms, methodologies

writing memory-efficient programs is possible, but very hard

Unsure:

what an embedded language is

numerical support -- not sure what you need

Title: Mission critical embedded language

Body:
Maybe the question sounds a bit strange, so I'll explain a the background a little bit.

Currently I'm working on a project at y university, which will be a complete on-board software for an satellite. The system is programmed in C++ on top of a real-time operating system. However, some subsystems like the attitude control system and the fault detection and a space simulation are currently only implemented in Matlab/Simulink, to prototype the algorithms efficiently. After their verification, they will be translated into c++.

The complete on-board software grew very complex, and only a handful people know the whole system. Furthermore, many of the students haven't program in C++ yet and the manual memory management of C++ makes it even more difficult to write mission critical software.

Of course the main system has to be implemented in C++, but I asked myself if it's maybe possible to use an embedded language to implement the subsystem which are currently written in Matlab. This embedded language should feature:

static/strong typing and compiler checks to minimize runtime errors

small memory usage, and relative fast runtime

attitude control algorithms are mainly numerical computations, so a good numeric support would be nice

maybe some sort of functional programming feature, matlab/simulink encourage you to use it too

I googled a bit, but only found Lua. It looks nice, but I would not use it in mission critical software. Have you ever encountered a situation like this, or do you know any language, which could satisfies the conditions?

EDIT: To clarify some things: embedded means it should be able to embed the language into the existing C++ environment. So no compiled languages like Ada or Haskell


问:
How is this "interface"-like structure/pattern called?
Let's assume we have an XmlDoc class that contains basic functionality for dealing with an XML data structure and saving/loading data to/from a file. Now we have several subclasses, A, B and C. They all inherit from XmlDoc and add component-specific methods for setting and getting lots of data. They are like "interfaces" but also add an implementation for the signatures.

Finally, we have an ABCDoc class that joins all the "interfaces" via virtual multiple inheritence and adds some ABCDoc-specific stuff, such as using XMLDoc-methods to set an appropriate doc type. We may also have an ADoc class for only saving A data.

How is this pattern called? "Interface" is not really the right word since interfaces usually do not contain an implementation.

Bonus points for C++ code conventions.

Body:
Multiple Inheritance.

Maybe what you are hightlighting its the fact that all the base classes for ABCDoc, are also subclasses of the same base class, and not different class hierarchies.

Actually, I think its a mixture of 2 techniques, first, extending a base class for several cases:

.................................................................................................................
.................................................................................................................
....+-----------------------------------------+................+----------------------------------------------+..
....|                <<class>>                |....../|........|                   <<class>>                  |..
....|             GenericDocument             |...../.|...+----|                  TextDocument                |..
....+-----------------------------------------+----<..|---+....+----------------------------------------------+..
....| [+]  Load(...)         <<virtual>>      |.....\.|...|....| [+]  Load(...)                 <<override>>  |..
....| [+]  Save(...)         <<virtual>>      |......\|...|....| [+]  Save(...)                 <<override>>  |..
....| [+]  DoSomething(...)  <<non virtual>>  |...........|....| [+]  SpecificMethod_A(...)  <<non virtual>>  |..
....+-----------------------------------------+...........|....+----------------------------------------------+..
..........................................................|......................................................
..........................................................|....+----------------------------------------------+..
..........................................................|....|                  <<class>>                   |..
..........................................................|----|                BitmapDocument                |..
..........................................................|....+----------------------------------------------+..
..........................................................|....| [+]  Load(...)                 <<override>>  |..
..........................................................|....| [+]  Save(...)                 <<override>>  |..
..........................................................|....| [+]  SpecificMethod_B(...)  <<non virtual>>  |..
..........................................................|....+----------------------------------------------+..
..........................................................|......................................................
..........................................................|....+----------------------------------------------+..
..........................................................+----|                   <<class>>                  |..
...............................................................|                  XMLDocument                 |..
...............................................................+----------------------------------------------+..
...............................................................| [+]  Load(...)                 <<override>>  |..
...............................................................| [+]  Save(...)                 <<override>>  |..
...............................................................| [+]  SpecificMethod_C(...)  <<non virtual>>  |..
...............................................................+----------------------------------------------+..
.................................................................................................................
.................................................................................................................

Second, having a single class that encapsulates all the existing scenarios.

..........................................................
..........................................................
....+----------------------------------------------+......
....|                   <<class>>                  +---+..
....|                  TextDocument                |...|..
....+----------------------------------------------+...|..
....| [+]  Load(...)                 <<override>>  |...|..
....| [+]  Save(...)                 <<override>>  |...|..
....| [+]  SpecificMethod_A(...)  <<non virtual>>  |...|..
....+----------------------------------------------+...|..
.......................................................|...................................................................
....+----------------------------------------------+...|.../|.....+-----------------------------------------------------+..
....|                  <<class>>                   |...|../.|.....|                       <<class>>                     |..
....|                BitmapDocument                |---+-<..|-----|                 MultipleFormatDocument              |..
....+----------------------------------------------+...|..\.|.....+-----------------------------------------------------+..
....| [+]  Load(...)                 <<override>>  |...|...\|.....| [+]  Load(...)                        <<override>>  |..
....| [+]  Save(...)                 <<override>>  |...|..........| [+]  Save(...)                        <<override>>  |..
....| [+]  SpecificMethod_B(...)  <<non virtual>>  |...|..........| [+]  SelectDefaultFileFormat(...)  <<non virtual>>  |..
....+----------------------------------------------+...|..........+-----------------------------------------------------+..
.......................................................|...................................................................
....+----------------------------------------------+...|..
....|                  <<class>>                   +---+..
....|                 XMLDocument                  |..
....+----------------------------------------------+..
....| [+]  Load(...)                 <<override>>  |..
....| [+]  Save(...)                 <<override>>  |..
....| [+]  SpecificMethod_C(...)  <<non virtual>>  |..
....+----------------------------------------------+..
......................................................

I have a similar case. A class is composed of several base classes,
that must descend from the same class, also.

I think there are 2 situations of these. If the intermediate base classes, can be consider to add more classes ("more file formats"), maybe the final class should be changed to this:

........................................................................................................................
....+-----------------------------------------+......./|......+-----------------------------------------------------+...
....|                <<class>>                |....../.|......|                       <<class>>                     |...
....|             GenericDocument             |-----<..|------|                 MultipleFormatDocument              |...
....+-----------------------------------------+......\.|......+-----------------------------------------------------+...
....| [+]  Load(...)         <<virtual>>      |.......\|......| [+]  Load(...)                        <<override>>  |...
....| [+]  Save(...)         <<virtual>>      |...............| [+]  Save(...)                        <<override>>  |...
....| [+]  DoSomething(...)  <<non virtual>>  |...............| [+]  SelectDefaultFileFormat(...)  <<non virtual>>  |...
....+------------------+----------------------+...............+-----------------------------------------------------+...
.......................|.................................................................^..............................
.......................|................................................................/.\.............................
.......................^.............................................................../...\............................
....................../.\..............................................................\.../............................
...................../...\..............................................................\./.............................
..................../-----\..............................................................V..............................
.......................+.................................................................|..............................
.......................|.................................................................|..............................
.......................|.......................................+-------------------------+---------------------------+..
.......................+---------------------------------------|                       <<class>>                     |..
...............................................................|                   <<Many classes>>                  |..
...............................................................+-----------------------------------------------------+..
...............................................................| [+]  Load(...)                        <<override>>  |..
...............................................................| [+]  Save(...)                        <<override>>  |..
...............................................................+-----------------------------------------------------+..
........................................................................................................................

Where it can support several file format classes like "add-ons".

There is a second situation.

In my app. the final class descend from 4 specific classes,
I had to have access to the specific methods of those intermediate classes,
and to add more classes didn't apply. And the 4 intermediate classes,
had to be descendant of the same base or root class.

If it was another language, that supported multiple inheritance interfaces,
maybe all these solutions could be more simple.

But, for the second case I "smell", an unnamed, Design Pattern.


答:
Ada is a very good mission critical language. In fact Esterline Avista in Platteville, Wisconsin uses ADA for their contracts with Boeing and are CMMI level 5 certified. The Universtity of Wisconsin Platteville currently teaches Ada as part of the CSSE department's Programming Language Structures class.

Ada was originally developed for the DoD from 1973 to 1983 and is used in avionics, railroad, banking, military, and space technologies.

Pros

Strongly Typed

Great for embedded systems

Great for real-time systems

object oriented

has high-level dynamic memory management

Cons

strange notion of OO

higher learning curve than other imperative or ALGOL-like languages

Title: Mission critical embedded language


答:
Anytime I've tried to learn a new language, I've found that reading code by people who know the language like the back of their hand, looking up/asking about anything that looks weird, and then trying to imitate their style is the best thing to do.  Examples:

In Python, since we're on the subject, I found the examples from Dive Into Python incredibly useful for getting started.  They tend to teach not only the basics of Python, but to really emphasize idiomatic Python.

When learning D, since the documentation wasn't great at the time because the language was so bleeding edge, I learned by reading the code to the standard library, specifically, some of Andrei Alexandrescu's masterpieces.

When learning C++ I inherited a codebase from a pretty good C++ programmer and learned a lot about idiomatic C++ programming from his insistence on passing STL containers by reference, etc.

In all languages, I find that browsing the StackOverflow questions about the language and looking at what people typically do to accomplish basic things helps.


问:
Is it bad idea to use flag variable to search MAX element in array?
Over my programming career I formed a habit to introduce a flag variable that indicates that the first  comparison has occured, just like Msft does in its linq Max() extension method implementation

```<code>public static int Max(this IEnumerable<int> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    int num = 0;
    bool flag = false;
    foreach (int num2 in source)
    {
        if (flag)
        {
            if (num2 > num)
            {
                num = num2;
            }
        }
        else
        {
            num = num2;
            flag = true;
        }
    }
    if (!flag)
    {
        throw Error.NoElements();
    }
    return num;
}
</code>```

However I have met some heretics lately, who implement this by just starting with the first element and assigning it to result, and oh no - it turned out that STL and Java authors have preferred the latter method.

Java:

```<code>public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();

    while (i.hasNext()) {
    T next = i.next();
    if (next.compareTo(candidate) > 0)
    candidate = next;
}
return candidate;
}
</code>```

STL:

```<code>template<class _FwdIt> inline
_FwdIt _Max_element(_FwdIt _First, _FwdIt _Last)
{   // find largest element, using operator<
_FwdIt _Found = _First;
if (_First != _Last)
    for (; ++_First != _Last; )
        if (_DEBUG_LT(*_Found, *_First))
            _Found = _First;
return (_Found);
}
</code>```

Are there any preferences between one method or another? Are there any historical reasons for this? Is one method more dangerous than another?

UPDATE: Please note, that the java version is capable of throwing exceptions with the line T candidate = i.next();and it's possible to get the same behavior in C# with the guard clause as it's shown in the second part of @ratchet freak's answer.

答:
There may well be preferences for one or the other; but one key distinction here is that the methods are not equivalent in semantics.  Particularly in their handling of empty lists.

The LINQ version must return a value, and therefore if the list is empty throws an exception.

The C++ version, on the other hand, returns an iterator.  That iterator may well point to the end() of the collection, and so any call has to be checked as to non-end-ness before using the result.

So the answer here is really more about how you expect to use the function, rather than its implementation.  Danger is in the eye of the beholder.  Exceptions vs. return and expectations are likely appropriate to their respective implementation philosophies.


答:
I'd suggest licensing, too.  On top of licensing, let's encrypt the source code of main routines using asymmetric key algorithm so that only your client's machine can run it.  One of the key in the pair be something obtained from the hardware (example: network card's serial number) of your client's machine.  Use the other key in the pair to decrypt the source code when running the program.  Note that the only deliverable in plaintext would be the decryption routine and the rest would be in ciphertext.

This way your client can copy-and-paste your seemingly gibberish code but can't run it elsewhere.  My suggestion is not completely bullet-proof however: the interpreter may store the decrypted program somewhere in memory.  Then it is possible that some hacker retrieve your program in plaintext during execution I guess.

As for preventing folders from root access, I agree that root can't be stopped from accessing any files/folders.

Title: How can I prevent a client from seeing my code written in an interpreted language?

Body:
I'm building a fairly complex interpreted program in Python. I've been working on most of this code for other purposes for a few months, and therefore don't want my client to be able to simply copy and try to sell it, as I think it's worth a fair amount.

The problem is that I need the script to run on a server that my client is paying for, so is there any way I can secure a particular folder on the machine from root access, or make it so only one particular use can access the directory? The OS is Ubuntu.


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答:
Choice

While I think your motives are good, I would recommend not deciding on an ergonomic keyboard and mouse, dual monitors, etc. One of the things that motivates good people is autonomy. I would look at getting them "the best" as much defined by the individuals as possible. This can easily be accomplished by giving people a budget and allowing them to spend it as they see fit.

While the team needs to agree on some things, common source control, open concept or private offices, there are plenty of things where there no advantage to everyone having the same thing. If someone want's a different chair and they're comparable in price, why not?


问:
Are there any empirical studies on the effect of different languages on software quality?
The proponents of functional programming languages assert that functional programming makes it easier to reason about code. Those in favor of statically typed languages say that their compilers catch enough errors to make up for the additional complexity of type systems. But everything I read on these topics is based on rational argument, not on empirical data.

Are there any empirical studies on what effects the different categories of programming languages have on defect rates or other quality metrics?

(The answers to this question seem to indicate that there are no such studies, at least not for the dynamic vs. static debate)

答: Although it's not related to code quality as such, this study looks at how novices learn using different languages. In particular, they compare how novices fare when learning Perl vs Quorum, a teaching language the authors wish to compare. What's really cool about this paper is that they actually come up with a control language where the syntax is generated randomly, as a sort of "placebo" language. This approach might be really interesting if applied to languages and code quality and help control some of those tricky confounding factors when comparing languages. </p>


答:
Use C++, do not use any embedded/layered anything.

I am going to answer the question in the negative, and tell you to use C++, hire appropriate resources, and do not layer something else on top.  Most of your criteria already fit C++ anyways: strong typing, minimal runtime, etc.  (Typing not as strong as Haskell, but better than most scripting languages)

You don't even need to use many classes and objects if you don't want to.  Write a more functional style, unless you need higher-order functions and currying.  There is no specific sin in using C++ as a better C, unless you do it by accident.  If you do it purposefully, then full steam ahead.

Given the presumed mission-criticality, you likely do not want to have the extra layers of complexity and points of failure that an embedded language will bring you.

That said: do write in as modern C++ as you are able, in particular using appropriate smart pointers (if you use heap memory) .  C++ has come a long way, and in particular most of the manual memory-management tasks are now better automated using shared_ptr, unique_ptr and the like.  If you have to write delete you are doing something wrong.

If you are stuck on wanting embedded something, have a look at Boost Proto.

Title: Mission critical embedded language


问:
Does syntax really matter in a programming language?
One of my professors says "the syntax is the UI of a programming language", languages like Ruby have great readability and it's growing, but we see a lot of programmers productive with C\C++, so as programmers does it really matter that the syntax should be acceptable?

I would love to know your opinion on that.

Disclaimer: I'm not trying to start an argument. I thought this is a good topic of discussion.

Update: This turns out to be a good topic. I'm glad you are all participating in it.

答:
Syntax matters to those who are learning it, the lower the barrier to entry the more popular the language might be initially. But if the language is difficult or impossible to express your self richly and succinctly it will start to wither in popularity.

Very terse and opaque ( Perl ) is just as bad as overly verbose and wordy ( AppleScript ).

There needs to be a balance, lower barrier to entry, high productivity and easy maintenance.


答:
The "Calling Object" is roughly equivalent to a dispatcher, so I guess you could use that term to describe it.

Methods are bound to a class, so "Calling Object" is redundant as Aaron points out.

Usually I think of "the Caller" as some code or object outside of the bound method.

Say I have a form called form1 and I create a instance of Puppy.  From form1 I called p.bark().  I would see the Calling object is form1.

I don't think there is a 100% correct answer here.


问:
Can anyone help solve this complex algorithmic problem?
I got this question in an interview and I was not able to solve it.

You have a circular road, with N number of gas stations.

You know the amount of gas that each station has.

You know the amount of gas you need to GO from one station to the next one.

Your car starts with 0.

You can only drive clockwise.

The question is: Create an algorithm, to know from which gas station you must start driving so that you complete a full circle.

As an exercise to me, I would translate the algorithm to C#.

答:
My first response would be "The requirements appear to be incomplete, are you sure you want me to write the code based on these requirements alone, shall we make them up as we go, or would you like my help completing the requirements before we design the software?".

The incomplete requires are, as stated in other questions,
Fuel capacity of the car.
End point - is it the start point or the station before the start point. (I think you answer this in your comment "complete a full circle implies end = start, in that case. I would clarify this as it is not explicit)
The question implies there is one, and only one solution, is this correct.

Other issues
Is performance of the algorithm a concern, or put another way, what is the budget for this project.

It's a good question - you cannot answer it in it's current form and be certain you have provided the customer with the solution to the problem he is expecting.