问:
Unique_ptr to hold memory for custom VM
I work for a company that use a custom DSL and my job is to port the VM to C++.

I'm trying to do this in compliance with the C++11 standard so i use auto when appropriate, the new for syntax, etc. But I'm having problem trying to "port" a part of the code that uses raw pointers to the new smart pointers.

On this DSL every object is derived from a base class called MObject, for example Numbers are handled by this class:

```<code>class MNumber : public MObject {
...
}
</code>```

The class responsible for handling the VM memory looks like this:

```<code>class Mallocator {
...
std::vector<MObject*> memory; //where all objects go...
</code>```

And to, for example, place a new MNumber in memory this is the function you call:

```<code>MNumber* Mallocator::newMNumber(double a) {
      MNumber* number = new MNumber {a};
      memory.push_back(number);
      INCRMEM(number); //updates memory usage and some other stuff
      return number;
</code>```

}

User defined variables are stored on a map like this: std::map<std::string, MObject*>
And steps executed by the VM to create a new user defined variable are more or less like this:

```<code>//storing a value on the VM stack
MNumber* number = allocator->newMNumber(...); //allocate the object
stack.push_back(number); //put a reference to the allocated value on the stack

//retrieving object from the stack and creating the variable
string var_name = codeobj->getVarName(instr.arg); //get the name of the variable from user code
value = stack.back(); // get the pointer to the allocated object from the stack
curr_frame->env->setVar(var_name, value); //associate the name to the object in the current scope
</code>```

It makes sense to me that the Mallocator object should hold ownership of every allocated MObject and the stack and the variables map should hold a "reference" to the allocated memory, since they only read the values. After searching the web for a few days and watching the Herb Sutter talk "Back to the Basics! Essentials of Modern C++ Style" i collected a few ideas:

On the newMNumber create a unique_ptr and use the .get() method to return a raw pointer. Wouldn't this defeat the purpose of using smart pointers?

On the newMNumber return a unique_ptr<MNumber>& and adapt the stack and map variables to work with unique_ptr<MObject>&

Use shared_ptr. I don't think shared_ptr is the solution because the ownership is not shared

Leave it the way it is and manage the pointers life-cycle myself (i'm already doing this anyway)

So my questions are: what is the right way to tackle this problem?
Is my design correct?
What other options i have?

PS1: Mallocator is a singleton and it is the sole responsible for allocating the objects and deleting objects from memory the rest of the VM only works with the pointers returned by Mallocator.

PS2: The language has more Objects than just numbers but since i can't share the whole code i've used MNumber as an example.

PS3: Some objects, like strings and integers, are cached so, for example, the function (not shown here) newMNumber(int a) only allow one object per integer to exist.

Thanks.

答:
On the newMNumber create a unique_ptr and use the .get() method to
  return a raw pointer. Wouldn't this defeat the purpose of using smart
  pointers?

No, no it would not.

The point of using smart pointers is about controlling who deletes the object, not who observes the object. It's perfectly fine under the smart pointer paradigm to observe the object owned by a smart pointer through a non-smart pointer or reference. In fact, this is a fairly common pattern that a class returns a non-owning pointer or reference to memory that it owns.

Title: Unique_ptr to hold memory for custom VM


问:
What algorithm-family or problem-space description fits? Industrial process feeding ingredients to process
Our process continuously feeds (normally <= 8) ingredients from a choice of hundreds, using 3 feeders only. So if ingredient count X is > 3, 3 through X are stirred together in a batch process and the resulting "premix" gets put in its own feeder. 6 is a hard limit for the number of ingredients a premix can have. It is possible to need to make 2 or even 3 premixes so that 2 or all 3 feeders feed premix. Unlikely but possible. This process is for experiments where we try 2 to 15 different recipes where we vary the ingredients and/or the weight-proportions. Hopefully this image conveys the situation.

A person is deciding what ingredients get their own feeder, what goes in the premix, what experimental runs have enough in common to share a big premix, and what order to do the runs in to minimize changes. I'd like to make Excel and VBA make all those decisions for her. I can code it up once I get my mind around the problem. I can even derive a symbolic system to describe it, but I'm sure someone smarter than me already has. However I don't know what family of problems this is from. Can you point me in the right direction?

答:
Welcome to the classic use case for Linear Programming and it's more straitlaced cousin, Constraint Programming. More specifically it's an example of a convex hull in the form of a combination. You'd use Linear Programming (possibly via constraint programming) to solve the problem of finding the area of a convex hull that fits your constraints.

There are many, many tools that can do this. Excel's particular variation on this is a plug-in called "Solver".

ContentLicense: CC BY-SA 3.0


问:
Naming conventions for instance, local and parameter variables
I was discussing with a senior developper coding conventions to apply to our projects (mainly Java/JEE projects). I disagreed with one convention he proposed:

Instance variable names should start with "_", local variables with
  "loc", and method parameters with "par", so it would be easy to identify
  a variable origin and scope.

While he put forward arguments for short-term memory and readability, I disagreed on the fact that it rather decreases readability, IDEs like Eclipse format variables differently depending on their type, and this problem would be avoided with a good class and method design.

Do you have any opinion, arguments or studies that supports my point (or opposes it)?

答:
This is an old question, but I'm going to post here anyway. I have some 20+ years of programming and dealing with other people's code.

I think that naming your variable with a short indication as to their scope is really really useful for the next person (or yourself) who will look at your code.

One does not already look at code in an IDE with pretty colors (and I can't remember what the colors means and different IDE show different colors, etc).

True, methods should be short enough so it's not loaded with tons of variables and tons of code but even on short one - when you look at code that is totally unfamiliar, it is sometimes hard to tell whether a variable is a class variable, local variable or method parameter.

To be able to distinguish at a glance makes it very easy to review the code you are unfamiliar with.

Take this example:

```<code>public <T> Page<T> moreLikeThis(MoreLikeThisQuery query, Class<T> clazz) {
    int startRecord = 0;
    ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
    String indexName = isNotBlank(query.getIndexName()) ? query.getIndexName() : persistentEntity.getIndexName();
    String type = isNotBlank(query.getType()) ? query.getType() : persistentEntity.getIndexType();

    Assert.notNull(indexName, "No 'indexName' defined for MoreLikeThisQuery");
    Assert.notNull(type, "No 'type' defined for MoreLikeThisQuery");
    Assert.notNull(query.getId(), "No document id defined for MoreLikeThisQuery");

    MoreLikeThisRequestBuilder requestBuilder = client.prepareMoreLikeThis(indexName, type, query.getId());

    if (query.getPageable() != null) {
        startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize();
        requestBuilder.setSearchSize(query.getPageable().getPageSize());
    }
    requestBuilder.setSearchFrom(startRecord);

    if (isNotEmpty(query.getSearchIndices())) {
        requestBuilder.setSearchIndices(toArray(query.getSearchIndices()));
    }
    if (isNotEmpty(query.getSearchTypes())) {
        requestBuilder.setSearchTypes(toArray(query.getSearchTypes()));
    }
    if (isNotEmpty(query.getFields())) {
        requestBuilder.setField(toArray(query.getFields()));
    }
    if (isNotBlank(query.getRouting())) {
        requestBuilder.setRouting(query.getRouting());
    }
    if (query.getPercentTermsToMatch() != null) {
        requestBuilder.setPercentTermsToMatch(query.getPercentTermsToMatch());
    }
    if (query.getMinTermFreq() != null) {
        requestBuilder.setMinTermFreq(query.getMinTermFreq());
    }
    if (query.getMaxQueryTerms() != null) {
        requestBuilder.maxQueryTerms(query.getMaxQueryTerms());
    }
    if (isNotEmpty(query.getStopWords())) {
        requestBuilder.setStopWords(toArray(query.getStopWords()));
    }
    if (query.getMinDocFreq() != null) {
        requestBuilder.setMinDocFreq(query.getMinDocFreq());
    }
    if (query.getMaxDocFreq() != null) {
        requestBuilder.setMaxDocFreq(query.getMaxDocFreq());
    }
    if (query.getMinWordLen() != null) {
        requestBuilder.setMinWordLen(query.getMinWordLen());
    }
    if (query.getMaxWordLen() != null) {
        requestBuilder.setMaxWordLen(query.getMaxWordLen());
    }
    if (query.getBoostTerms() != null) {
        requestBuilder.setBoostTerms(query.getBoostTerms());
    }

    SearchResponse response = requestBuilder.execute().actionGet();
    return resultsMapper.mapResults(response, clazz, query.getPageable());
}
</code>```

Now, time yourself and look at the code (extracted from ElasticsearchTemplate from the spring-data-elasticsearch project - the code I was reviewing which prompted me to search on Google for what people say about naming conventions).

What's the scode of resultsMapper?

Is requestBuilding a parameter?

etc...

Here is my simple suggestion on how variables should be named:

Class static attributes (i.e. constants): ALL_CAPS_WITH_UNDERSCORES (e.g. HOST_NAME).

Class attributes (i.e. class instance variables): camelCase (e.g. resultsMapper).

Method parameters: prefixed with a (e.g. aQuery, aClazz).

Local variables: prefixed with my (e.g. myIndexName, myType).

The code above becomes:

```<code>public <T> Page<T> moreLikeThis(MoreLikeThisQuery aQuery, Class<T> aClazz) {
  int myStartRecord = 0;
  ElasticsearchPersistentEntity myPersistentEntity = getPersistentEntityFor(aClazz);
  String myIndexName = isNotBlank(aQuery.getIndexName()) ? aQuery.getIndexName() : myPersistentEntity.getIndexName();
  String myType = isNotBlank(aQuery.getType()) ? aQuery.getType() : myPersistentEntity.getIndexType();

  Assert.notNull(myIndexName, "No 'indexName' defined for MoreLikeThisQuery");
  Assert.notNull(myType, "No 'type' defined for MoreLikeThisQuery");
  Assert.notNull(aQuery.getId(), "No document id defined for MoreLikeThisQuery");

  MoreLikeThisRequestBuilder myRequestBuilder = client.prepareMoreLikeThis(myIndexName, myType, aQuery.getId());

  if (aQuery.getPageable() != null) {
     myStartRecord = aQuery.getPageable().getPageNumber() * aQuery.getPageable().getPageSize();
     myRequestBuilder.setSearchSize(aQuery.getPageable().getPageSize());
  }
  myRequestBuilder.setSearchFrom(myStartRecord);

  if (isNotEmpty(aQuery.getSearchIndices())) {
     myRequestBuilder.setSearchIndices(toArray(aQuery.getSearchIndices()));
  }
  if (isNotEmpty(aQuery.getSearchTypes())) {
     myRequestBuilder.setSearchTypes(toArray(aQuery.getSearchTypes()));
  }
  if (isNotEmpty(aQuery.getFields())) {
     myRequestBuilder.setField(toArray(aQuery.getFields()));
  }
  if (isNotBlank(aQuery.getRouting())) {
     myRequestBuilder.setRouting(aQuery.getRouting());
  }
  if (aQuery.getPercentTermsToMatch() != null) {
     myRequestBuilder.setPercentTermsToMatch(aQuery.getPercentTermsToMatch());
  }
  if (aQuery.getMinTermFreq() != null) {
     myRequestBuilder.setMinTermFreq(aQuery.getMinTermFreq());
  }
  if (aQuery.getMaxQueryTerms() != null) {
     myRequestBuilder.maxQueryTerms(aQuery.getMaxQueryTerms());
  }
  if (isNotEmpty(aQuery.getStopWords())) {
     myRequestBuilder.setStopWords(toArray(aQuery.getStopWords()));
  }
  if (aQuery.getMinDocFreq() != null) {
     myRequestBuilder.setMinDocFreq(aQuery.getMinDocFreq());
  }
  if (aQuery.getMaxDocFreq() != null) {
     myRequestBuilder.setMaxDocFreq(aQuery.getMaxDocFreq());
  }
  if (aQuery.getMinWordLen() != null) {
     myRequestBuilder.setMinWordLen(aQuery.getMinWordLen());
  }
  if (aQuery.getMaxWordLen() != null) {
     myRequestBuilder.setMaxWordLen(aQuery.getMaxWordLen());
  }
  if (aQuery.getBoostTerms() != null) {
     myRequestBuilder.setBoostTerms(aQuery.getBoostTerms());
  }

  SearchResponse myResponse = myRequestBuilder.execute().actionGet();
  return resultsMapper.mapResults(myResponse, aClazz, aQuery.getPageable());
</code>```

}

Is that perfect? I don't think so. But the above, as far as variables are concerned, is now easier to read. There are other things such as alignment and spacing, which I won't get into in this answer as it is not related to the question, which would make it easier to read as well.

You don't like Camel Case? Fine, use underscores, etc, but prefix your local variables and your parameters to make them different than class instance variables.

You don't like a and my - fine, just stay consistent within your project and use something else... but do use something.

Rule #1: consistency within the project.

Rule #2: make it easy to read and don't require the reader to know everything before he can learn.

Body:
This is an old question, but I'm going to post here anyway. I have some 20+ years of programming and dealing with other people's code.

I think that naming your variable with a short indication as to their scope is really really useful for the next person (or yourself) who will look at your code.

One does not already look at code in an IDE with pretty colors (and I can't remember what the colors means and different IDE show different colors, etc).

True, methods should be short enough so it's not loaded with tons of variables and tons of code but even on short one - when you look at code that is totally unfamiliar, it is sometimes hard to tell whether a variable is a class variable, local variable or method parameter.

To be able to distinguish at a glance makes it very easy to review the code you are unfamiliar with.

Take this example:

public <T> Page<T> moreLikeThis(MoreLikeThisQuery query, Class<T> clazz) {
    int startRecord = 0;
    ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
    String indexName = isNotBlank(query.getIndexName()) ? query.getIndexName() : persistentEntity.getIndexName();
    String type = isNotBlank(query.getType()) ? query.getType() : persistentEntity.getIndexType();

    Assert.notNull(indexName, "No 'indexName' defined for MoreLikeThisQuery");
    Assert.notNull(type, "No 'type' defined for MoreLikeThisQuery");
    Assert.notNull(query.getId(), "No document id defined for MoreLikeThisQuery");

    MoreLikeThisRequestBuilder requestBuilder = client.prepareMoreLikeThis(indexName, type, query.getId());

    if (query.getPageable() != null) {
        startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize();
        requestBuilder.setSearchSize(query.getPageable().getPageSize());
    }
    requestBuilder.setSearchFrom(startRecord);

    if (isNotEmpty(query.getSearchIndices())) {
        requestBuilder.setSearchIndices(toArray(query.getSearchIndices()));
    }
    if (isNotEmpty(query.getSearchTypes())) {
        requestBuilder.setSearchTypes(toArray(query.getSearchTypes()));
    }
    if (isNotEmpty(query.getFields())) {
        requestBuilder.setField(toArray(query.getFields()));
    }
    if (isNotBlank(query.getRouting())) {
        requestBuilder.setRouting(query.getRouting());
    }
    if (query.getPercentTermsToMatch() != null) {
        requestBuilder.setPercentTermsToMatch(query.getPercentTermsToMatch());
    }
    if (query.getMinTermFreq() != null) {
        requestBuilder.setMinTermFreq(query.getMinTermFreq());
    }
    if (query.getMaxQueryTerms() != null) {
        requestBuilder.maxQueryTerms(query.getMaxQueryTerms());
    }
    if (isNotEmpty(query.getStopWords())) {
        requestBuilder.setStopWords(toArray(query.getStopWords()));
    }
    if (query.getMinDocFreq() != null) {
        requestBuilder.setMinDocFreq(query.getMinDocFreq());
    }
    if (query.getMaxDocFreq() != null) {
        requestBuilder.setMaxDocFreq(query.getMaxDocFreq());
    }
    if (query.getMinWordLen() != null) {
        requestBuilder.setMinWordLen(query.getMinWordLen());
    }
    if (query.getMaxWordLen() != null) {
        requestBuilder.setMaxWordLen(query.getMaxWordLen());
    }
    if (query.getBoostTerms() != null) {
        requestBuilder.setBoostTerms(query.getBoostTerms());
    }

    SearchResponse response = requestBuilder.execute().actionGet();
    return resultsMapper.mapResults(response, clazz, query.getPageable());
}

Now, time yourself and look at the code (extracted from ElasticsearchTemplate from the spring-data-elasticsearch project - the code I was reviewing which prompted me to search on Google for what people say about naming conventions).

What's the scode of resultsMapper?

Is requestBuilding a parameter?

etc...

Here is my simple suggestion on how variables should be named:

Class static attributes (i.e. constants): ALL_CAPS_WITH_UNDERSCORES (e.g. HOST_NAME).

Class attributes (i.e. class instance variables): camelCase (e.g. resultsMapper).

Method parameters: prefixed with a (e.g. aQuery, aClazz).

Local variables: prefixed with my (e.g. myIndexName, myType).

The code above becomes:

public <T> Page<T> moreLikeThis(MoreLikeThisQuery aQuery, Class<T> aClazz) {
  int myStartRecord = 0;
  ElasticsearchPersistentEntity myPersistentEntity = getPersistentEntityFor(aClazz);
  String myIndexName = isNotBlank(aQuery.getIndexName()) ? aQuery.getIndexName() : myPersistentEntity.getIndexName();
  String myType = isNotBlank(aQuery.getType()) ? aQuery.getType() : myPersistentEntity.getIndexType();

  Assert.notNull(myIndexName, "No 'indexName' defined for MoreLikeThisQuery");
  Assert.notNull(myType, "No 'type' defined for MoreLikeThisQuery");
  Assert.notNull(aQuery.getId(), "No document id defined for MoreLikeThisQuery");

  MoreLikeThisRequestBuilder myRequestBuilder = client.prepareMoreLikeThis(myIndexName, myType, aQuery.getId());

  if (aQuery.getPageable() != null) {
     myStartRecord = aQuery.getPageable().getPageNumber() * aQuery.getPageable().getPageSize();
     myRequestBuilder.setSearchSize(aQuery.getPageable().getPageSize());
  }
  myRequestBuilder.setSearchFrom(myStartRecord);

  if (isNotEmpty(aQuery.getSearchIndices())) {
     myRequestBuilder.setSearchIndices(toArray(aQuery.getSearchIndices()));
  }
  if (isNotEmpty(aQuery.getSearchTypes())) {
     myRequestBuilder.setSearchTypes(toArray(aQuery.getSearchTypes()));
  }
  if (isNotEmpty(aQuery.getFields())) {
     myRequestBuilder.setField(toArray(aQuery.getFields()));
  }
  if (isNotBlank(aQuery.getRouting())) {
     myRequestBuilder.setRouting(aQuery.getRouting());
  }
  if (aQuery.getPercentTermsToMatch() != null) {
     myRequestBuilder.setPercentTermsToMatch(aQuery.getPercentTermsToMatch());
  }
  if (aQuery.getMinTermFreq() != null) {
     myRequestBuilder.setMinTermFreq(aQuery.getMinTermFreq());
  }
  if (aQuery.getMaxQueryTerms() != null) {
     myRequestBuilder.maxQueryTerms(aQuery.getMaxQueryTerms());
  }
  if (isNotEmpty(aQuery.getStopWords())) {
     myRequestBuilder.setStopWords(toArray(aQuery.getStopWords()));
  }
  if (aQuery.getMinDocFreq() != null) {
     myRequestBuilder.setMinDocFreq(aQuery.getMinDocFreq());
  }
  if (aQuery.getMaxDocFreq() != null) {
     myRequestBuilder.setMaxDocFreq(aQuery.getMaxDocFreq());
  }
  if (aQuery.getMinWordLen() != null) {
     myRequestBuilder.setMinWordLen(aQuery.getMinWordLen());
  }
  if (aQuery.getMaxWordLen() != null) {
     myRequestBuilder.setMaxWordLen(aQuery.getMaxWordLen());
  }
  if (aQuery.getBoostTerms() != null) {
     myRequestBuilder.setBoostTerms(aQuery.getBoostTerms());
  }

  SearchResponse myResponse = myRequestBuilder.execute().actionGet();
  return resultsMapper.mapResults(myResponse, aClazz, aQuery.getPageable());

}

Is that perfect? I don't think so. But the above, as far as variables are concerned, is now easier to read. There are other things such as alignment and spacing, which I won't get into in this answer as it is not related to the question, which would make it easier to read as well.

You don't like Camel Case? Fine, use underscores, etc, but prefix your local variables and your parameters to make them different than class instance variables.

You don't like a and my - fine, just stay consistent within your project and use something else... but do use something.

Rule #1: consistency within the project.

Rule #2: make it easy to read and don't require the reader to know everything before he can learn.


问:
Infix vs Prefix Notation - Which do you prefer?
I have been learning Clojure and looking at Scheme and CL which introduced me to the world of prefix notation. At first I didn't like it but it is still starting to grow on me. To be honest though, there are still long calculations that are difficult for me to understand but I think that is an issue of me needing more exposure/practice and I'll get it.

But that leads me to the question: Which type of notation do you prefer and why?

答:
I have no preference. I can work well in either.

Not many programmers realize that prefix notation is actually the norm and infix is the oddball. After all, just about every language uses prefix notation for function/method calls. It's only a relatively small number of arithmetic and logic operators that are infix.

The more you look at our system of mathematical symbols, the more screwy you see they are. Some are infix (+, -, *), some are postfix (x2), some prefix (tan x), some under-fix (ratios and fractions), and some overfix. It's not as simple as PEMDAS.

ContentLicense: CC BY-SA 2.5


问:
Should I avoid using 'break' during a coding interview?
I have an upcoming internship interview with Microsoft and, although I rarely use break in my own code, it does simplify things a lot of times and bring me to a solution faster when coding on the whiteboard.

To anyone familiar with the interview process, would it reflect badly on my coding style? I'm not asking about whether breaks are bad or not in general, but should I try to go for Boolean checks instead during the interview?

答:
I once asked that question to a friend whom is currently employed at microsoft (at was at the time employed in the team working on Project Volta, now known as "Reactive Extensions"), because at university my lecturers used to say that "breaks are bad". He had a chuckle and said it was probably a lecturer whom never wrote industry code.

Seeing as they use breaks in code, I don't see why writing it in an interview would reflect badly, as long as you understand the advantages and/or disadvantages in the scenario they asked you to work out.

Being able to know why you opted for one or the other will show insight, which is important. Imagine your insight in the problem and general solution was great, but you used a break, that's easy to fix. They just tell you not to use breaks anymore. On the other hand, if you didn't use breaks, but the algorithm was otherwise sloppy, that'll be worse for your odds.

It'll depend on the problem at hand as well though, and like World engineer wrote as a comment, on a lot of other variables as well.


问:
what is the difference between inclusion and inheritance
the question is self explanatory, I just want to know when to use the inclusion and when to use inheritance, and which one serves for re-usability.

in other words, which one meets the Object Oriented programming principles the most?

答:
I think you might be confusing the terms. Inclusion is actually a form of inheritance, it basically says that if you a type T, then subtype T1 and subtype T2 can be sent the same messages.

Perhaps you wanted to know the difference between object aggregation/composition and inheritance? If so, then in general favor aggregation and composition over inheritance asit often prevents restructuring base classes if requirements change.

If you want to know more, then I recommend reading the GoF (Gang of Four)'s book Design Patterns: Elements of Reusable Design, or try Head First Design Patterns which is a bit easier to read and understand.


答:
Along with use of semicolons in Javascript, whether to use vi or emacs in the Unix world and whether to use a single return statement in a function it's a controversy that often doesn't make sense to most production coders. If it makes sense to use it and the code remains clear, then I think you'll be fine. If not, then don't use it.

Now knowing the arguments for and against using break is probably more useful if it gets brought up in an interview.

Title: Should I avoid using 'break' during a coding interview?

Body:
I have an upcoming internship interview with Microsoft and, although I rarely use break in my own code, it does simplify things a lot of times and bring me to a solution faster when coding on the whiteboard.

To anyone familiar with the interview process, would it reflect badly on my coding style? I'm not asking about whether breaks are bad or not in general, but should I try to go for Boolean checks instead during the interview?


答:
Personally, I would frown upon break outside of switch statements. But that said, I would frown more if the code was wrong. If break is what you're used to and you can produce functional code with it, go nuts. It shouldn't disqualify you from any job.

It's hard enough to find competent programmers. Competent programmers that code in my preferred style are more like unicorns.


答:
This question is at risk of being a duplicate of Are `break` and `continue` bad programming practices? but I will try to give a more theoretical explanation.

I forgot the reference but I would appreciate if someone can find it and I will be happy to include it here, or you can edit into my answer without asking if you have the reps.

The theoretical explanation was originally given to support some limited use of goto, and the justification to these limited usage later gave rise to the structured control flow statements we're familiar today.

The justification is this. Perform the following exercise on paper:

For the purpose of this exercise, treat all control transfers (both unconditional and conditional) as goto.

List the program code for a single function. If you would like to analyze more than one function, inline it into the top-level function.

Draw arrows to connect each goto to the branch target.

Put all backward- (upward-) going branch arrows on the left of the program listing.

Put all forward- (downward-) going branch arrows on the right of the program listing.

If you can figure out a way to arrange those arrows without any two crisscross each other, your code is said to have a sensible control transfer structure.

(The terminology used here may have diverged from the original reference.)

Now let's examine the two keywords being questioned: break and continue.

I assume that your are referring to their use inside loops. As others point out, break is mandatory in switch statements (or at least your future employer's coding standards would have made that mandatory), so there is no point in arguing.

break is simply a control transfer to the bottom (exit) of the loop. Therefore it does not crisscross the control flow of the loop itself.

continue transfers to the top (loop advance and condition test) of the loop. If the condition test is false it also exits the loop. Note that the "if condition test fails ..." part is a different control flow. continue only needs to transfer to the top.

Simply put, break and continue used inside a loop doesn't violate the sensible control flow structure. This is why they are allowed in the first place in historically significant languages such as Pascal, etc where language design trumps practical considerations.

Now, regarding some posts saying that break is bad if it appears in the middle of some non-side-effect-free code - I would say yes and no.

Most of the time, if you see this happening, it is because it has to be so. The reality makes this argument moot.

Example: in some of your code, you have to do this inside a loop:

Check condition A first. If it fails you can do break (or continue, depending on the task).

Only if condition A is satisfied, you can start computing some value B.

With B computed, you will also check condition B (using the value of B).

Can you move the condition check B to the top of the loop? You can't. It's dictated by the nature of the task you are implementing. Thus the argument is moot. If at all, that argument favors decomposing long functions into shorter subroutines, rather than arguing for careful positioning of the use of break statements.


问:
Query on usage of 'Window()' default constructor from java.awt
I had been through this query before asking this question.

In class Window we have constructor with default direct access level  package private but not private as shown below:

```<code>Window() throws HeadlessException {
        GraphicsEnvironment.checkHeadless();
        init((GraphicsConfiguration)null);
    }
</code>```

With class dummy inheriting  class Window,

```<code>import java.awt.*;

public class dummy extends Window{
    dummy() {

    }
}
</code>```

I see this error: Implicit super constructor Window() is not visible. Must explicitly invoke another constructor

I designed non-public class with zero-arg constructor having default direct access level  package private and the subclass constructor invokes zero-arg Superclass constructor without any error.

I would like to understand,

Why does the compiler show this error despite the direct access level to the constructor Window(){} is package private?

Note: I am using jdk 1.6

答:
For the same reason as in the linked question: the constructor is package-private. It cannot be accessed outside of the java.awt package, and I assume your class is not in that package.

In this case I have to wonder why you would be extending the Window class to begin with. In general, one should always use AWT and Swing by assembling standard components. It is fairly rare to be in a situation where it is necessary to create a subclass for any AWT or Swing class. Often it is a sign of using the frameworks incorrectly: for example, subclassing JFrame in order to set the frame's title in the constructor and to add components, when both actions are perfectly fine to perform in another class (create JFrame using the string constructor, call add() with subcomponents).


答:
This is my advice, and it has nothing to do with whether using break is good or bad: Code the way you code. They want to know how you code, not how you think they code.

You may be thinking that it's best to outsmart the interviewer by telling them what they want to hear. In a worst case scenario they'll hire you, and then you'll look like an idiot because you gave a wrong impression and don't write the same type of code they expected, and they'll fire you a few miserable months later for failing to live up to their expectations.

Be honest in an interview. If they don't hire you because of your coding style, that's a win all the way around. They don't get someone that doesn't fit with the way they work, and you don't get stuck in a job where you have to write code in a way that is unfamiliar to you, where you're ridiculed for your coding style, and where you're constantly worried they will find out you're not who you pretended to be during the interview.

That, and be prepared to explain why you used break, and why you think that was the right or wrong choice. As an interviewer, I don't care so much about what the candidates say or write on the whiteboard, as long as they can give me a rational explanation for their choice.


问:
Can a Java interface declaration enforce parameter properties?
As far as I know, declaring an interface is like so:

```<code>public interface Roots_Squares {
    public double square_root( double value );
}
</code>```

Now... how do you enforce value to have non-negative values?  Such a function should avoid negative values right?  If someone creates a class that implements this, and that implementation does not handle negative values, and then I use their class with a negative value... well, things break.

It then becomes my responsibility to check for negatives when I'm pretty sure the implementor should do the checking.

答:
Doval's answer is outdated now. You can use an enforce parameter properties(check arguments) in the interface:</p>

```<code>public interface Math {
    /**
     * @throws IllegalArgumentException if value <= 0
     */
    default public void sqrt(Double value) {
        if(value <= 0) throw new IllegalArgumentException("value must be greater than 0");
        squareRoot(value);
    }

    public void squareRoot(Double value);
}
</code>```

Body:
Doval's answer is outdated now. You can use an enforce parameter properties(check arguments) in the interface:

public interface Math {
    /**
     * @throws IllegalArgumentException if value <= 0
     */
    default public void sqrt(Double value) {
        if(value <= 0) throw new IllegalArgumentException("value must be greater than 0");
        squareRoot(value);
    }

    public void squareRoot(Double value);
}


问:
Why 'JButton' is-a 'Container' in javax.swing?
As per the class hierarchy in java.awt.*, class Button & class Label is-a class Component, and Component is not a Container, which make sense to me.

As per the redesign of class hierarchy in javax.swing.*, class JButton is-a class JComponent in-turn class JComponent is-a class Container,

So, What does it mean to say that, class JButton or class JRadioButton is-a class Container?  How could one think of using button or radiobutton as container in GUI programming?

Note: I am java beginner.

答:
What does it mean to say that, class JButton or class JRadioButton is-a class Container?

The reason why all Swing components are derived from java.awt.Container is mostly for practical reasons which are internal to the implementation of Swing. AWT and Swing usually will not be mixed. But internally, a Swing component might realize itself using more than one AWT component, and that's purely up to the Swing component itself.

How could one think of using button or radiobutton as container in GUI programming?

The fact that Swing components extend java.awt.Container can and should mostly be ignored. One shouldn't mess around with the java.awt.Container methods of Swing components unless it's obvious that it makes sense (which is the case for most if not all *Pane components and javax.swing.JPanel).


答:
In general I would agree to favor composition over inheritance.  You can think of composition as a "has-a" relationship and inheritance as an "is-a" relationship.  Composition helps manage complexity by keeping each class separate and only aggregating what you need.

One drawback to composition is that you may find yourself having to write a number of proxy "forwarding" methods for your composed classes.

I find a good rule of thumb is that if a class really is a type of the base class and needs most or all of the base class functionality exposed, these are good reasons to consider using inheritance.

Title: what is the difference between inclusion and inheritance

Body:
the question is self explanatory, I just want to know when to use the inclusion and when to use inheritance, and which one serves for re-usability.

in other words, which one meets the Object Oriented programming principles the most?


问:
Should I accept empty collections in my methods that iterate over them?
I have a method where all logic is performed inside a foreach loop that iterates over the method's parameter:

```<code>public IEnumerable<TransformedNode> TransformNodes(IEnumerable<Node> nodes)
{
    foreach(var node in nodes)
    {
        // yadda yadda yadda
        yield return transformedNode;
    }
}
</code>```

In this case, sending in an empty collection results in an empty collection, but I'm wondering if that's unwise.

My logic here is that if somebody is calling this method, then they intend to pass data in, and would only pass an empty collection to my method in erroneous circumstances.

Should I catch this behaviour and throw an exception for it, or is it best practice to return the empty collection?

答:
The method is named TransformNodes. In case of an empty collection as input,
getting back an empty collection is natural and intuitive,
and makes prefect mathematical sense.

If the method was named Max and designed to return the maximum element, then it would be natural to throw NoSuchElementException on an empty collection, as the maximum of nothing makes no mathematical sense.

If the method was named JoinSqlColumnNames and designed to return a string where the elements are joined by a comma to use in SQL queries, then it would make sense to throw IllegalArgumentException on an empty collection, as the caller would eventually get an SQL error anyway if he used the string in an SQL query directly without further checks, and instead of checking for a returned empty string he really should have checked for empty collection instead.


问:
Database design for polymorphic data
I have an application that needs to log communications with users over several different mediums: Email, SMS, Voice, Website Announcements, etc.. in a traditional database.

I have considered 3 approaches to modeling these different types of data:

Single Table Inheritance:

Store them all together in a single table (i.e., comm_message) with discriminator field of some sort to indicate the type of communications (e.g. message_type).  This means that some fields in the table won't be used for each type--and it means that the same message may be duplicated in several different rows in the table (if the message is sent via more than one medium).

Message "has" transports

Have a message table (comm_message) and then transports table (comm_transports) with the various different mediums of communication.  A many-to-many relationship between messages and transports would mean one row for each message in the message table--but that row might have several different transports.  If additional specific information is needed for a particular transport, it could be in it's own table (i.e. comm_sms, comm_email, etc..) that is linked off the many-to-many table. I.e., a "has-a" approach.

Class Table Inheritance:

Create a base message table (comm_message) and then another table for each medium with fields specific to it (inheritance).  My ORM (LLBLGen) would facilitate this approach by using shared PKs for the different tables.  In this approach there would be a row in the base table (comm_message), plus rows in each of the related tables for each transport (comm_email, comm_sms, etc.) but there would be no many-to-many relationship.  Rather the records across different tables would share the same PK (1-1).  This would be more of an "is-a" approach.

Context:  This is a medium sized application (around 100 tables) that I'll be maintaining for many years--so I'd like to get this "right".  I'll often need to present all the communications info together in the UI in a grid, reports, etc..

Which should I use?  Why?

答:
Follow composition over inheritance as composition lends itself well to relational databases.

Say you want to get all short messages:

```<code>SELECT * FROM Message INNER JOIN ShortMessage ON ShortMessage.message = Message.id
</code>```

Say you want to get all short messages and emails:

```<code>SELECT * FROM Message
   LEFT OUTER JOIN ShortMessage ON ShortMessage.message = Message.id
   LEFT OUTER JOIN Email ON Email.message = Message.id
</code>```

This will effectively create a result set very much like what your first option is, with a lot of null fields.

So the basic idea here is that a message potentially has a email. Depending on whether or not you define Email.message to be UNIQUE, you can make sure there's at most one email corresponding to a message. This setup (like all alternatives you proposed) allows a single message to have multiple different transports, which is actually conceivable in the real world.

Advantages of this approach:

(over 1 & 2) Your database is normalized, which usually gives you stuff for free

if you want to add new transport types without altering any existing tables (not something you want to do in a huge database)

You don't have to store loads of nulls

(over 3) You can query all messages in one query, so you can get all messages to a specific recipient like so:

```<code>SELECT IFNULL(Email.body, ShortMessage.body) as text FROM Message
  LEFT OUTER JOIN ShortMessage ON ShortMessage.message = Message.id
  LEFT OUTER JOIN Email ON Email.message = Message.id
  WHERE
    Email.recepient = "john.doe@example.com"
    OR ShortMessage.recipient = "01189998819991197253"
</code>```

And voilà, you've got yourself a list of all text ever sent to john doe.

However, if you're using an ORM, you might actually use the power to perform queries such as that. I am have no practical experience with C#, but from my understanding as an outsider, Linq lends itself well to accessing relational databases for what they are, instead of trying to shoehorn objects semantics onto records (which always makes you hit a very thick wall at some point down the road).

ContentLicense: CC BY-SA 4.0

Title: Database design for polymorphic data

Body:
Follow composition over inheritance as composition lends itself well to relational databases.

Say you want to get all short messages:

SELECT * FROM Message INNER JOIN ShortMessage ON ShortMessage.message = Message.id

Say you want to get all short messages and emails:

SELECT * FROM Message
   LEFT OUTER JOIN ShortMessage ON ShortMessage.message = Message.id
   LEFT OUTER JOIN Email ON Email.message = Message.id

This will effectively create a result set very much like what your first option is, with a lot of null fields.

So the basic idea here is that a message potentially has a email. Depending on whether or not you define Email.message to be UNIQUE, you can make sure there's at most one email corresponding to a message. This setup (like all alternatives you proposed) allows a single message to have multiple different transports, which is actually conceivable in the real world.

Advantages of this approach:

(over 1 & 2) Your database is normalized, which usually gives you stuff for free

if you want to add new transport types without altering any existing tables (not something you want to do in a huge database)

You don't have to store loads of nulls

(over 3) You can query all messages in one query, so you can get all messages to a specific recipient like so:

SELECT IFNULL(Email.body, ShortMessage.body) as text FROM Message
  LEFT OUTER JOIN ShortMessage ON ShortMessage.message = Message.id
  LEFT OUTER JOIN Email ON Email.message = Message.id
  WHERE
    Email.recepient = "john.doe@example.com"
    OR ShortMessage.recipient = "01189998819991197253"

And voilà, you've got yourself a list of all text ever sent to john doe.

However, if you're using an ORM, you might actually use the power to perform queries such as that. I am have no practical experience with C#, but from my understanding as an outsider, Linq lends itself well to accessing relational databases for what they are, instead of trying to shoehorn objects semantics onto records (which always makes you hit a very thick wall at some point down the road).


问:
What is the difference between user requirements and system requirements?
From what I've read I believe user requirements are just the system requirements given in lay mans terms, is this correct? I'm specifically referring to the book "Software Engineering" by Ian Sommerville which I am obligated to follow. Given the example below from said book, why is there not a user requirement to match the second system requirement. For example "the user requires the report to be generated after 17.30 on the last working day of the month." To me that is still in natural language so it is readable by the user. How much detail should be included in a user requirement vs system requirement and where do you draw the line?

User Requirement Definition:

```<code>1. The MHC-PMS shall generate monthly management reports showing
   the cost of drugs prescribed by each clinic during that month.
</code>```

System Requirements Specification:

```<code>1.1. On the last working day of each month, a summary of the drugs
     prescribed, their cost, and the prescribing clinics shall be generated.
1.2. The system shall automatically generate the report for printing after
     17.30 on the last working day of the month.
</code>```

答:
I'll speak to your examples.

The first example of a "user requirement" is more like a wish or "feature."  The way you can tell the difference between a feature and a requirement is that there's enough detail in the requirement to make it testable.  Requirement 1 is not testable because, well, it's a wish.  "I wish that the system had some reports for the managers."  How do you know that the requirement has been achieved, that you can declare success?

Requirement 1.1 is testable because you can wait until the last working day of the month, and see if a report is generated on that day (or you can inject dates into the system and observe its behavior).

Requirement 1.2 is testable for the same reasons.

Neither system requirement, however, tells you what the reports should look like, how the data is laid out, or how the calculations are made; they only describe the reports in general terms.  In practice, there will be a Software Design Specification of some sort that tells you in detail what these reports will look like.


答:
User requirements tell what application must/should do to satisfy user's needs. It a list of features an application must/should have, and it is used a guidance when you develop an application: then all points are checked, you are (probably) done.

I tend to call this simply the "list of features".

System requirements tell what system should have to be able to run the program:

Hardware: CPU, memory, disk space, etc.

Software: OS, libraries, packages, etc.

There is a bit of confusion:

In "user requirements" the user is a subject, the one that require, and the program being developed is an object.

In "system requirements" the program being developed is a subject (and it's not even mentioned in a phrase), while "system" is an object.

The word "system" can refer to different things:

software being developed

physical device which runs the software being developed

network of such devices

OS together with execution environment

The thing you've called "System Requirements Specification" is probably something like the Software requirements specification - I consider that to be a superset of user requirements.

Title: What is the difference between user requirements and system requirements?

Body:
From what I've read I believe user requirements are just the system requirements given in lay mans terms, is this correct? I'm specifically referring to the book "Software Engineering" by Ian Sommerville which I am obligated to follow. Given the example below from said book, why is there not a user requirement to match the second system requirement. For example "the user requires the report to be generated after 17.30 on the last working day of the month." To me that is still in natural language so it is readable by the user. How much detail should be included in a user requirement vs system requirement and where do you draw the line?

User Requirement Definition:

```<code>1. The MHC-PMS shall generate monthly management reports showing
   the cost of drugs prescribed by each clinic during that month.
</code>```

System Requirements Specification:

```<code>1.1. On the last working day of each month, a summary of the drugs
     prescribed, their cost, and the prescribing clinics shall be generated.
1.2. The system shall automatically generate the report for printing after
     17.30 on the last working day of the month.
</code>```


问:
How do you go about training a replacement?
I recently asked about leaving a position and got a lot of great answers. One of the common threads was that being around to train the new person would be expected and could go a long way.

Now considering that (I think) most people don't stay at a company for a long time after they've given notice, and it will take time for the company to interview/hire one - that leaves for a short amount of time to get someone up to speed.

I've also never trained anyone before. I did a bunch of tutoring in University and College, but teaching a language/technology is far different from training someone to replace you on your job.

So the question is: how do you go about training someone to replace you in a, potentially, short amount of time?

答:
Point them at the wiki

You do have one, don't you? And I'm sure you have a few team members who act as code librarians during the code reviews so that common code can be introduced (either into the company code library or to replace the custom code that the developer has just knocked together).

No? Ah. Well, you've got a problem then.

Depending on how much time you've got, you'll need to follow one of these plans, in order of the level of crisis:

1. Aargh! I'm leaving this afternoon

If the new guy is highly experienced in your problem domain, then just point him at the wiki and show him how to get to the relevant code in your SCM. Buy him a beer, offer your phone number if you're feeling generous and toddle off to your leaving party.

If he's not so experienced, introduce him to other members of the team who should be his primary points of contact to get an idea of how it all fits together. That's about all you've got time for.

2. Got all week, but there's a lot of tidying up

Get your replacement to shadow you for the first day so you can assess their skills and try to get them doing your job as quickly as possible. Let them see how you tackle a problem, and then gradually hand over so that they are solving it and you are acting as a consultant. Build out from the core operations you do every day to the less frequent ones. Make up problems if you can. Pair program if you're able to. Get them to keep track of what you've told them in a wiki or some other networked text-based resource so they can refer to it later, and eventually turn it into proper documentation.

3. It's the junior developer who's taking over

They'll already have the domain knowledge and know how the team works. Start allocating them your tasks and working to build their knowledge about unfamiliar systems and processes. Concentrate on helping them get the basics down pat, with the more advanced stuff coming later as you get time.

Provide basic telephone support

Assuming that you're leaving on good terms with the company, offer to provide them with some telephone support so they know that you're not leaving them in the lurch. If they start ringing at every hour asking bone-headed questions that could be found on the wiki then mention your competitive consultancy rates. Otherwise, the odd call here and there allows them to pick your brains and you to stay in touch with them, which could be handy when the next round of jobs comes up.


问:
Why aren't there code overviews for open-source projects?
There are very complex open source projects out there, and to some of them I think I could make some contributions, and I wish I could, but the barrier to entry is too high for a single reason: for changing one line of code at a big project you have to understand all of it.

You don't need to read all the code (even if you read, it won't be sufficient) and understand all every single line does and why, because the code probably is modularized and compartimentized, so there are abstractions in place, but even then you need to get an overview of the project so you can know where are the modules, where does one module interface with other, what exactly each module do and why, and in which directories and files are each of these things happening.

I'm calling this code overview, as the name of a section that open source projects could have in the website or documentation explaining their code to outsiders. I think it would benefit potential contributors, as they would be able to identify places where they could build, the actual primary coders involved, as they would be able to, while writing everything, reorganize their minds, and would help users, as they would be help to understand and better report bugs they experience and maybe even become contributors.

But still I have never seen one of these "code overviews". Why? Are there things like these and I'm missing them? Things that do the same job as I am describing? Or is this a completely useless idea, as everybody, except for me, can understand projects with thousands lines of code easily?

答:
Overview documents such as you describe are rare even on commercial projects.  They require extra effort with little value for the developers.  Also developers tend not to write documentation unless they really need to.  Some projects are lucky to have members who are good at technical writing, and as a result have good user documentation. Developer documentation if it exists, is unlikely to be updated to reflect code changes.

Any well organized project will have a directory tree which is relatively self-explanatory.  Some projects will document this hierarchy and/or the reasons it was chosen.  Many projects follow relatively standard code layouts, so if you understand one you will understand the layout of other projects using the same layout.

To change a line of code you need a limited understanding of the surrounding code.  You should never have to understand the whole code base in order do so.  If you have a reasonable idea of the kind of function that is broken, it is often possible to navigate the directory hierarchy rather quickly.

To change a line of code you need to understand the method within which the line is found.  If you understand what the expected behavior of the method is, you should be able to make corrective changes, or extensions to the functionality.

For languages which provide scoping, you can refactor private scoped methods. In this case you will be may need to change callers as well as the refactor method or methods.  This requires a broader, but still limited, understanding of the code base.

See my article Adding SHA-2 to tinyca for an example of how such changes can be done.  I have an extremely limited understanding of the code used to generate the interface.


答:
Because it's extra effort to create and maintain such a document, and too many people don't understand the associated benefits.

Many programmers aren't good technical writers (although many are); they rarely write documents strictly for human consumption, therefore they don't have practice and don't like doing it. Writing a code overview takes time that you can't spend on coding, and the initial benefit to a project is always greater if you can say "We support all three encoding variants" rather than "We have really neat explanations of our code!" The notion that such a document will attract more developers so that in the long run more code will get written isn't exactly foreign to them, but it's perceived as an uncertain gamble; will this text really make the difference between snagging a collaborator or not? If I keep coding right now, we will certainly get this thing done.

A code overview document can also make people feel defensive; it's hard to describe higher-level decisions without feeling the need to justify them, and very often people make decisions without a reason that "sounds good enough" when actually written own. There's also an effect related to the aforementioned one: since updating the text to suit the changing code causes additional effort, this can discourage sweeping changes to the code. Sometimes this stability is a good thing, but if the code really does need a mid-level rewrite, it turns into a liability.

Title: Why aren't there code overviews for open-source projects?

Body:
There are very complex open source projects out there, and to some of them I think I could make some contributions, and I wish I could, but the barrier to entry is too high for a single reason: for changing one line of code at a big project you have to understand all of it.

You don't need to read all the code (even if you read, it won't be sufficient) and understand all every single line does and why, because the code probably is modularized and compartimentized, so there are abstractions in place, but even then you need to get an overview of the project so you can know where are the modules, where does one module interface with other, what exactly each module do and why, and in which directories and files are each of these things happening.

I'm calling this code overview, as the name of a section that open source projects could have in the website or documentation explaining their code to outsiders. I think it would benefit potential contributors, as they would be able to identify places where they could build, the actual primary coders involved, as they would be able to, while writing everything, reorganize their minds, and would help users, as they would be help to understand and better report bugs they experience and maybe even become contributors.

But still I have never seen one of these "code overviews". Why? Are there things like these and I'm missing them? Things that do the same job as I am describing? Or is this a completely useless idea, as everybody, except for me, can understand projects with thousands lines of code easily?


问:
Is there an alternative to instanceof when filtering a Java stream by class?
I have an unexpected situation in a project in which all types extending one class are packed into a Java collection; but only a specific extension of that class contains an additional method. Let's call it "also()"; and let me be clear that no other extension has it. Right before performing one task on every item in that collection, I need to call also() on every item that implements it.

The easiest way forward is this:

```<code>stuff.stream().filter(item -> item instanceof SpecificItem)
            .forEach(item -> ((SpecificItem)item).also()));
stuff.stream().forEach(item -> item.method());
</code>```

It works fine, but I'm not comfortable with the "instanceof" in there. That's generally a marker of bad code smell. It is very possible that I will refactor this class just to get rid of it. Before I do something that dramatic, though, I thought I would check with the community and see if someone with more experience with either Streams or Collections had a simpler solution.

As an example (certainly nonexclusive), is it possible to get a view of a collection that filters entries by class?

答:
It's hard to give specific recommendations without knowing what SpecificItem and also() actually are, but:

Define also() on the superclass of SpecificItem. Give it a default implementation which does nothing (give it an empty method body). Individual subclasses can override it if desired. Depending on what also actually is, you may need to rename it to something which makes sense for all the classes involved.


问:
Ideal data structure/techniques for storing generic scheduler data in C#
I am trying to implement a generic scheduler object in C# 4 which will output a table in HTML. Basic aim is to show some object along with various attributes, and whether it was doing something in a given time period.

The scheduler will output a table displaying the headers:

Detail Field 1 ....N| Date1.........N

I want to initialise the table with a start date and an end date to create the date range (ideally could also do other time periods e.g. hours but that isn't vital). I then want to provide a generic object which will have associated events.

Where an object has events within the period I want a table cell to be marked

E.g.

```<code>Name Height Weight 1/1/2011 2/1/2011 3/1/20011...... 31/1/2011
Ben  5.11    75       X        X                       X
Bill 5.7     83                X        X
</code>```

So I created scheduler with Start Date=1/1/2011 and end date 31/1/2011

I'd like to give it my person object (already sorted) and tell it which fields I want displayed (Name, Height, Weight)

Each person has events which have a start date and end date. Some events will start and end outwith but they should still be shown on the relevant date etc.

Ideally I'd like to have been able to provide it with say a class booking object as well. So I'm trying to keep it generic.

I have seen Javasript implementations etc of similar.

What would a good data structure be for this? Any thoughts on techniques I could use to make it generic. I am not great with generics so any tips appreciated.

答:
I don't think this is too tough.  What am I missing?

```<code>using System;
using System.Collections.Generic;

public class ScheduledPerson {
    public string Name {get; set;}

    public Dictionary<string, Object> Fields {
        get { return _fields; }
        set { _fields = value; }
    }
    private Dictionary<string, Object> _fields = new Dictionary<string, Object>();

    public List<Tuple<DateTime, DateTime>> Events {
        get { return _events; }
        set { _events = value; }
    }
    private List<Tuple<DateTime, DateTime>> _events = new List<Tuple<DateTime, DateTime>>();

    public ScheduledPerson(string name){
        Name = name;
    }
}
</code>```

I don't see a good way to make our ScheduledPerson classes generic, as it seems the fields can be anything. I'm storing the field values as Objects, as I see nothing that requires them to be dynamics.  Just make sure all field value types have a sensible ToString() implementation.

If you want Events to be a List of DateRange or of your own Event class instead of Tuple, feel free.

It then remains for you to write a separate class to render each ScheduledPerson in a table, along with figuring out all the headers from all ScheduledPerson records.  It you are dealing with ten thousand people, you'll want a better solution that has all the headers stored, but for most applications, it won't be too bad to enumerate all the Fields on all the ScheduledPersons to figure out the headers.

Body:
I don't think this is too tough.  What am I missing?

using System;
using System.Collections.Generic;

public class ScheduledPerson {
    public string Name {get; set;}

    public Dictionary<string, Object> Fields {
        get { return _fields; }
        set { _fields = value; }
    }
    private Dictionary<string, Object> _fields = new Dictionary<string, Object>();

    public List<Tuple<DateTime, DateTime>> Events {
        get { return _events; }
        set { _events = value; }
    }
    private List<Tuple<DateTime, DateTime>> _events = new List<Tuple<DateTime, DateTime>>();

    public ScheduledPerson(string name){
        Name = name;
    }
}

I don't see a good way to make our ScheduledPerson classes generic, as it seems the fields can be anything. I'm storing the field values as Objects, as I see nothing that requires them to be dynamics.  Just make sure all field value types have a sensible ToString() implementation.

If you want Events to be a List of DateRange or of your own Event class instead of Tuple, feel free.

It then remains for you to write a separate class to render each ScheduledPerson in a table, along with figuring out all the headers from all ScheduledPerson records.  It you are dealing with ten thousand people, you'll want a better solution that has all the headers stored, but for most applications, it won't be too bad to enumerate all the Fields on all the ScheduledPersons to figure out the headers.


问:
Do the implementations of the Node interface in Web API violate Liskov Substitution Principle?
MDN article on Node interface states that

interfaces [that inherit from Node interface] may return null in particular cases where the methods and properties are not relevant. They may throw an exception - for example when adding children to a node type for which no children can exist.

To me it seems like a strengthening of preconditions in a subtype - a violation of LSP.

Do these implementations actually violate LSP, or is my understanding incorrect?

答:
Technically: no, this is not a violation of the LSP: The type Node gives us some guarantees here: Any method may work as documented below or return null or throw an exception. Any subtype of Node must still live by this contract.

In practice: yes, this is a questionable design. The DOM interface seems to use a variant of the Composite Pattern, and the design shows it's age. Today, it is not considered a best practice to have “optional methods” that don't have to be provided by a subtype. However, this does keep the number of types more manageable, and in statically typed languages removes the need for frequent casting – note that the DOM is not only used in JavaScript.


问:
Specific empty children classes
Is having empty children classes, just to specify, a bad practice?

Lets suppose I've a generic Product class. There are electrical, electronic and mechanical products. I need to represent all them and must be able to differ each one in some operations.
I've two options:

add a member named "type" in Product class to specify whether it's a electrical, electronic or mechanical product.

create children classes of Product, one for each kind of product: ElectricalProduct, ElectronicProduct and MechanicalProduct. As these classes don't differ from each other in methods or members - already defined in parent class - they would be all empty.

I consider second option a better approach, but is it the right way? I've never seen such thing on any application or library.

What do you thing? Any suggestion?

Edit:

Here is an example of doing it using second option: https://gist.github.com/tsouzar/c2ffebbcdad30920bf06

I can't see a better way of doing it, but I don't know if it is a good practice to have that empty classes.

答:
I think it's best to have one Product class with a type field, for a few reasons:

If you ever need to serialize/deserialize in a way that the language doesn't natively support, there's only one constructor; you don't need to switch on the type and use one of several constructors.

There's a slight benefit to readability - if readers see ElectricalProduct they might wonder if it contains special logic, and have to open it to see that it doesn't.

You can make Product final (Java) or sealed (C#), which is good for efficiency - certain method invocations won't need to go through a vtable.

That said, if you think you might later add some logic specific to certain product types, then separate classes might be better so that you can do so without a major refactor.

Title: Specific empty children classes


问:
Is there a name for an internal incorrect behaviour that does not manifest itself as a bug?
To put this in context, I have the following scenario. I am writing a Common Lisp program that works with strings and lists of characters.

In a certain function foo, the value of a variable suff is a list of characters. Further on in the code, I forgot that suff was a list and treated it as a string, calling

```<code>(subseq suff 0 1)
</code>```

I did not notice the mistake, because subseq works both on strings and lists:

```<code>CL-USER> (subseq "abc" 0 1)
"a"

CL-USER> (subseq '(#\a #\b #\c) 0 1)
(#\a)
</code>```

So in the subsequent code I assumed I was working with strings while in fact I was moving around lists of characters.

These wrongly-typed results were finally formatted by the program's output function using (concatenate 'string .... I was lucky, because concatenate happily produces a string when given lists of characters as arguments.

I only discovered this mistake when adding more tests (yes, I know, TDD, but that's another topic) and testing foo directly.

Since my program was running properly - at the time my output function was the only piece of code that was using the corrupted data - I cannot say that the program as a whole contained a bug even though function foo, taken separately, was buggy.

Is there a special name to describe such an incorrect internal behaviour that does not manifest externally as a bug?

答: That'd be a logic error.  See the wiki article for more information.</p>


答:
A bug is a bug even when no one has found it.

According with this wikipedia article:

A software bug is an error, flaw, failure, or fault in a computer
  program or system that causes it to produce an incorrect or unexpected
  result, or to behave in unintended ways.

The behavior was not what you intended, so it's a bug. You may call it a latent bug, a dormant bug, etc.

Some bugs have only a subtle effect on the program's functionality,
  and may thus lie undetected for a long time.

According to that article, the bug you talk about could be classified as a "resource bug", meaning:

Using an otherwise valid instruction on the wrong data type

In conclusion, what hasn't yet manifested itself externally, is really a dormant bug, waiting for an specific situation to manifest itself, usually in a production environment and during a weekend.

Title: Is there a name for an internal incorrect behaviour that does not manifest itself as a bug?

Body:
To put this in context, I have the following scenario. I am writing a Common Lisp program that works with strings and lists of characters.

In a certain function foo, the value of a variable suff is a list of characters. Further on in the code, I forgot that suff was a list and treated it as a string, calling

```<code>(subseq suff 0 1)
</code>```

I did not notice the mistake, because subseq works both on strings and lists:

```<code>CL-USER> (subseq "abc" 0 1)
"a"

CL-USER> (subseq '(#\a #\b #\c) 0 1)
(#\a)
</code>```

So in the subsequent code I assumed I was working with strings while in fact I was moving around lists of characters.

These wrongly-typed results were finally formatted by the program's output function using (concatenate 'string .... I was lucky, because concatenate happily produces a string when given lists of characters as arguments.

I only discovered this mistake when adding more tests (yes, I know, TDD, but that's another topic) and testing foo directly.

Since my program was running properly - at the time my output function was the only piece of code that was using the corrupted data - I cannot say that the program as a whole contained a bug even though function foo, taken separately, was buggy.

Is there a special name to describe such an incorrect internal behaviour that does not manifest externally as a bug?


问:
Cleaner C# without unneeded indents
In OO languages, at least C#, everything has to be in a class. Sometimes, everything is in a namespace as well.

Just about literally all the code in one class is going to be automatically indented by a tab stop or two, which is seriously pretty pointless if it doesn't help with code readability.

The issue with just removing the indent on every single line is that the one/two lines that had the "class ..." and the "}" become out of place.

What seems like a clean and readable way to remove the extra indents in front of every single line without making the class declarations be weird?

This might be opinion-based but I don't know.

答:
You could leave a blank line between the class declaration and the class body, with the bracket at the end of the line, like so:</p>

```<code>class ThisIsAClass {

public void thisIsAFunction {
    // Do stuff
}

}
</code>```

Title: Cleaner C# without unneeded indents

Body:
You could leave a blank line between the class declaration and the class body, with the bracket at the end of the line, like so:

class ThisIsAClass {

public void thisIsAFunction {
    // Do stuff
}

}


答: Try setting a tab equal to two spaces. It cuts back on whitespace by a factor of 2.5x, yet it provides more than enough visual feedback.</p>

Title: Cleaner C# without unneeded indents

Body:
In OO languages, at least C#, everything has to be in a class. Sometimes, everything is in a namespace as well.

Just about literally all the code in one class is going to be automatically indented by a tab stop or two, which is seriously pretty pointless if it doesn't help with code readability.

The issue with just removing the indent on every single line is that the one/two lines that had the "class ..." and the "}" become out of place.

What seems like a clean and readable way to remove the extra indents in front of every single line without making the class declarations be weird?

This might be opinion-based but I don't know.


答:
Do as Defenestrator suggested, in leaving a blank line between the class declaration and the first member and also give a comment end braces:</p>

```<code>class ThisIsAClass {

public void thisIsAFunction {
    // Do stuff
}// end thisIsAFunction

}// end class ThisIsAClass
</code>```

Title: Cleaner C# without unneeded indents

Body:
Do as Defenestrator suggested, in leaving a blank line between the class declaration and the first member and also give a comment end braces:

class ThisIsAClass {

public void thisIsAFunction {
    // Do stuff
}// end thisIsAFunction

}// end class ThisIsAClass


答:
I've always heard them called "latent bugs".

On all the teams I've worked on, it's good practice to identify latent bugs and fix them before someone experiences them.

In the situation you describe, it may or may not be a problem, if the language is just working around the oversight. But if the way it's working causes a performance problem because it's breaking things up and reassembling them the long way, then that is undesirable behavior, and is fair game to flag as a bug, even if the explicit output is correct.


答:
I think the reason you are having trouble with which path to take is because there is a fundamental design flaw here. You have anemic classes here, which is itself an OO anti-pattern. The external logic that is switching on the type needs to be brought into the Product family of classes.

The code smell for this is that, no matter which path you go, you will either need to check a type member or instanceof in other places in your code. The other smell is that you will constantly be querying a Product object for data and making decisions based on it (see tell-don't-ask). This means that it will be difficult to modify or add behavior because you will be needing to make changes in many, disparate places rather than in an appropriate class to hold that behavior for each type.

Edit:

The addition of the code details shows there is a little more nuance to your question. Let's start by looking at what we are talking about by "type" of product.

Traditionally, anytime we hear the word "type", we jump to the object concept of Type (which I will capitalize to differentiate). This Type is associated with polymorphic behavior, inheritance, encapsulation, and all the other object-oriented concepts. Here, though, we aren't necessarily describing a Type. We are talking about what looks to be a data attribute called a type. The behavior does not really change based on the type, only the value.

As an example to compare against, we can look at integers. We have ints 1 and 2. The behaviors between them are exactly the same; only the values differ. This means that we shouldn't have an abstract type for int that is implemented as a int1 concrete type and an int2 concrete type, etc. We need one concrete type for all ints, and a simple way to interact between them (like comparison for sorting). Your idea of a product type is the same.

If your products have or will have distinct, polymorphic behaviors, inheritance is a valid solution. Here, though, your type is only a data attribute, like the price and the brand, with no difference in behavior. Therefore, you should have a type attribute like you have a price attribute and a brand attribute.

Ideally, you will want to make your code more open-closed, so there should be a way to do this as elegantly as possible. We can create an enum containing the different types of products that exist, ordered in the order they need to be output (using a static std::set or similar on product might be easier to work with, if you'd rather). The type attribute of the product will point to an enum value. In your product_manager class, instead of three named vectors, you should have a map/dictionary-type structure to map from type enum to the respective vector, generated from the elements in the enum. This way, that structure will automatically add vectors for each type at instantiation. When you add a product, select the vector to add it to based on the type of the product. Then you can iterate over the map, then over each vector to print out the products, grouped by type.

Pseudocode:

```<code>enum product_type { electrical, electronic, mechanical }

class product {
    //...

    get_type() {
        return this.type;
    }

    //...
}

class product_manager {
    map<product_type, vector<product>> products;

    product_manager() {
        foreach(p_type in product_type) {
            products.insert(p_type, new vector<product>);
        }
    }

    //...

    add_product(product p) {
        products.at(p.get_type()).append(p);
    }

    //...

    print_products() {
        foreach(p_type in product_type) {
            foreach(product in products.at(p_type)) {
                print_product(product);
            }
        }
    }

    //...
}
</code>```

If you never want to use the type anywhere else, you can make it private, and make the product_manager a friend to product.

I also want to make a quick point about the example code you posted.

```<code>//in real application we don't know instantiation proccess, so don't know what type of product comes to us.
test::electrical_product *ep = new test::electrical_product;
test::electronic_product *etp = new test::electronic_product;
test::mechanical_product *mp = new test::mechanical_product;

// set products' members values

pm.add_product(ep);
pm.add_product(etp);
pm.add_product(mp);

pm.print_electrical_products();
pm.print_electronic_products();
pm.print_mechanical_products();
</code>```

You use method overloading with different parameter types to determine which implementation to call. The trouble with this is that, in your real application, all the products would be of type abstract_product *. The compiler routes the method calls based on the compile-time type of the object, meaning any products being added would be sent to a method product_manager.add_product(abstract_product *) instead of the overloaded methods, meaning that it would not do what you intend.

Title: Specific empty children classes

Body:
Is having empty children classes, just to specify, a bad practice?

Lets suppose I've a generic Product class. There are electrical, electronic and mechanical products. I need to represent all them and must be able to differ each one in some operations.
I've two options:

add a member named "type" in Product class to specify whether it's a electrical, electronic or mechanical product.

create children classes of Product, one for each kind of product: ElectricalProduct, ElectronicProduct and MechanicalProduct. As these classes don't differ from each other in methods or members - already defined in parent class - they would be all empty.

I consider second option a better approach, but is it the right way? I've never seen such thing on any application or library.

What do you thing? Any suggestion?

Edit:

Here is an example of doing it using second option: https://gist.github.com/tsouzar/c2ffebbcdad30920bf06

I can't see a better way of doing it, but I don't know if it is a good practice to have that empty classes.

Body:
I think the reason you are having trouble with which path to take is because there is a fundamental design flaw here. You have anemic classes here, which is itself an OO anti-pattern. The external logic that is switching on the type needs to be brought into the Product family of classes.

The code smell for this is that, no matter which path you go, you will either need to check a type member or instanceof in other places in your code. The other smell is that you will constantly be querying a Product object for data and making decisions based on it (see tell-don't-ask). This means that it will be difficult to modify or add behavior because you will be needing to make changes in many, disparate places rather than in an appropriate class to hold that behavior for each type.

Edit:

The addition of the code details shows there is a little more nuance to your question. Let's start by looking at what we are talking about by "type" of product.

Traditionally, anytime we hear the word "type", we jump to the object concept of Type (which I will capitalize to differentiate). This Type is associated with polymorphic behavior, inheritance, encapsulation, and all the other object-oriented concepts. Here, though, we aren't necessarily describing a Type. We are talking about what looks to be a data attribute called a type. The behavior does not really change based on the type, only the value.

As an example to compare against, we can look at integers. We have ints 1 and 2. The behaviors between them are exactly the same; only the values differ. This means that we shouldn't have an abstract type for int that is implemented as a int1 concrete type and an int2 concrete type, etc. We need one concrete type for all ints, and a simple way to interact between them (like comparison for sorting). Your idea of a product type is the same.

If your products have or will have distinct, polymorphic behaviors, inheritance is a valid solution. Here, though, your type is only a data attribute, like the price and the brand, with no difference in behavior. Therefore, you should have a type attribute like you have a price attribute and a brand attribute.

Ideally, you will want to make your code more open-closed, so there should be a way to do this as elegantly as possible. We can create an enum containing the different types of products that exist, ordered in the order they need to be output (using a static std::set or similar on product might be easier to work with, if you'd rather). The type attribute of the product will point to an enum value. In your product_manager class, instead of three named vectors, you should have a map/dictionary-type structure to map from type enum to the respective vector, generated from the elements in the enum. This way, that structure will automatically add vectors for each type at instantiation. When you add a product, select the vector to add it to based on the type of the product. Then you can iterate over the map, then over each vector to print out the products, grouped by type.

Pseudocode:

enum product_type { electrical, electronic, mechanical }

class product {
    //...

    get_type() {
        return this.type;
    }

    //...
}

class product_manager {
    map<product_type, vector<product>> products;

    product_manager() {
        foreach(p_type in product_type) {
            products.insert(p_type, new vector<product>);
        }
    }

    //...

    add_product(product p) {
        products.at(p.get_type()).append(p);
    }

    //...

    print_products() {
        foreach(p_type in product_type) {
            foreach(product in products.at(p_type)) {
                print_product(product);
            }
        }
    }

    //...
}

If you never want to use the type anywhere else, you can make it private, and make the product_manager a friend to product.

I also want to make a quick point about the example code you posted.

//in real application we don't know instantiation proccess, so don't know what type of product comes to us.
test::electrical_product *ep = new test::electrical_product;
test::electronic_product *etp = new test::electronic_product;
test::mechanical_product *mp = new test::mechanical_product;

// set products' members values

pm.add_product(ep);
pm.add_product(etp);
pm.add_product(mp);

pm.print_electrical_products();
pm.print_electronic_products();
pm.print_mechanical_products();

You use method overloading with different parameter types to determine which implementation to call. The trouble with this is that, in your real application, all the products would be of type abstract_product *. The compiler routes the method calls based on the compile-time type of the object, meaning any products being added would be sent to a method product_manager.add_product(abstract_product *) instead of the overloaded methods, meaning that it would not do what you intend.


问:
Algorithm Analysis: In practice, do coefficients of higher order terms matter?
Consider an^2 + bn + c. I understand that for large n, bn and c become insignificant.

I also understand that for large n, the differences between 2n^2 and n^2 are pretty insignificant compared to the differences between, say n^2 and n*log(n).

However, there is still an order of 2 difference between 2n^2 and n^2. Does this matter in practice? Or do people just think about algorithms without coefficients? Why?

答: Yes, constant factors matter very much in practice. Big-O notation is only the first step(albeit highly useful) in measuring the performance of an algorithm/program. An algorithm that takes only n^2 steps is certainly preferable to one that takes 2*n^2 steps, all things else being equal.</p>


答:
What matters is subjective.  However, you are correct that the coefficients are not of the first order of significance.  The coefficients are often ignored mostly because there isn't as much potential to improve an algorithm by worrying about them.

Consequently, I wouldn't mind reworking code to get n^2 down to n*log(n).  But going from 2n*log(n) to n*log(2n) is not something I'd be willing to make my code harder to read over.

Title: Algorithm Analysis: In practice, do coefficients of higher order terms matter?

Body:
Consider an^2 + bn + c. I understand that for large n, bn and c become insignificant.

I also understand that for large n, the differences between 2n^2 and n^2 are pretty insignificant compared to the differences between, say n^2 and n*log(n).

However, there is still an order of 2 difference between 2n^2 and n^2. Does this matter in practice? Or do people just think about algorithms without coefficients? Why?


答:
You are describing a semantic error.  One that was not caught by your language and did not cause a problem with the proper execution of the software.

Whenever you write code you are writing for many audiences that need to be satisfied.  You satisfied your language and your user.  You failed to satisfy your maintenance developer.

Semantics are about meaning.  By forgetting to treat suff as a list you wrote code whose meaning is difficult to understand.  The fact that the end result is identical is no more correct than if you got the correct answer on a math test by forgetting a negative twice.  Most professors would mark you down for that because they are looking for meaning in your answer, not luck.

Anyone looking at your code later (including you) will feel the same way.  Code that works but makes no sense is a special kind of frustrating.

Unfortunately if you search on semantic errors you'll mostly find the ones that the programming languages catch for you.  As you've discovered, not every kind of semantic error can be caught automaticly.

If you had violated the semantics intentionally, just to make something that works, then it could easily be called a kludge.  Infact, anyone reading your code and not knowing your intent could justifiably call it one.


答:
Besides being extra effort, some open source project are crippling their documentations on purpose, in order to get freelancing jobs for their maintainers (to implement something, or to hold trainings). Not only they don't have code overview, but their API and tutorials are bad or missing lots of things.

Just to name one quite popular : bluez. Good luck finding a good tutorial, other then to scan for nearby devices.


问:
Intermediate results as variables or only base values?
I have a object which has a few base variables (integers as example) and one intermediate variable for further processing. The intermediate variable can be calculated from the base vars. Now the question: Should I always repeat the calculation of the intermediate var from the base vars or should I save the value and only change it if the base vars change? (I need access to every var in pseudo random order.)

Two examples in C++-Code.

Caching the result:

```<code>class Test
{
  private:
    int a;
    int b;
    int c;

    int x;

    void calcX ()
    {
        // Just an example for a calculation for x.
        x = ((a + 10) * (b / (c*c + 1)));
    }

  public:
    void setA (int var)
    {
        a = var;
        calcX();
    }
    void setB (int var)
    {
        b = var;
        calcX();
    }
    void setC (int var)
    {
        c = var;
        calcX();
    }

    // Every var has a get methode.
}
</code>```

Always recalculating the result:

```<code>class Test
{
  private:
    int a;
    int b;
    int c;

    int x;

  public:
    // Var a, b and c have get and set methodes.

    int getX ()
    {
        return ((a + 10) * (b / (c*c + 1)));
    }
}
</code>```

So, which way is considered better? I really don't know. We should not save the intermediate value because it would be redundant, but then again we should not recalculate the value again and again.

答:
It depends.

If you need to calculate once, and use million times, then the answer is obvious: the first case wins.

If you need to calculate every time, or quite often, then pick what you prefer. Your function doesn't read from a file, and has no slow operations, so it will not make a huge difference.

Avoid premature optimization.

When optimizing, it is best to measure. Profile the code and optimize only the bottlenecks. Everything else is a microoptimization, and should be avoided.


问:
What argument passing mechanism does python use, and where is this officially documented?
As far as I am aware, python is generally referred to as 'call-by-sharing', but does it implement this with call-by-value (like Java) or call-by-reference? or something else? I would appreciate if this could be answered with official python documentation (in which I can't seem to find the answer) as opposed to anything subjective.</p>

答:
You can just ask Python herself:

```<code>def is_python_pass_by_value(foo):
    foo.append('More precisely, for reference types, it is call-by-object-sharing.')
    foo = ['Python is pass-by-reference.']

quux = ['Yes, of course, Python *is* pass-by-value!']

is_python_pass_by_value(quux)

print(quux)
# ['Yes, of course, Python *is* pass-by-value!', 'More precisely, for reference types, it is call-by-object-sharing.']
</code>```

Call-by-sharing is simply a special case of pass-by-value, where the value being passed is an implicit pointer to shared (not necessarily mutable) state.

Body:
You can just ask Python herself:

def is_python_pass_by_value(foo):
    foo.append('More precisely, for reference types, it is call-by-object-sharing.')
    foo = ['Python is pass-by-reference.']

quux = ['Yes, of course, Python *is* pass-by-value!']

is_python_pass_by_value(quux)

print(quux)
# ['Yes, of course, Python *is* pass-by-value!', 'More precisely, for reference types, it is call-by-object-sharing.']

Call-by-sharing is simply a special case of pass-by-value, where the value being passed is an implicit pointer to shared (not necessarily mutable) state.


问:
Should I use a class as a wrapper?
Lets say I have a class representing a chemical compound

```<code>class Compound(networkx.Graph):

    def __init__(self):
        super(Compound, self).__init__()
</code>```

And lets say that I want to add some extra functionality onto a chemical compound.  It should probably inherit from Compound.  But is it okay to just use it as a wrapper for Compound?  For example

```<code>class Acid(Compound):

    def __init__(self, compound, *other_data):
        self.__dict__.update(compound.__dict__)
</code>```

Basically, this class would just have pointers to the underlying class and then let me add functionality without having to copy things.  Does this make sense?  Is it reasonable? Am I even doing it right?

答:
You should probably use inheritance in this case, but wrapping the object you with to extend is fine as well. In fact, the technique is useful enough to have a name: the Decorator Pattern.

The usual way to forward all calls in Python is not to mess around with __dict__, but to override __getattr__ ("explicit is better than implicit"):

```<code>class A(object):
    def __init__(self, *args, **kwargs):
        self._b = B(*args, **kwargs)

    def __getattr__(self, name):
        return getattr(self._b, name)
</code>```

__getattr__ only fires when the name is not found the usual way, so you are free to add or override names in A which you do not want to be forwarded to B.

Title: Should I use a class as a wrapper?

Body:
You should probably use inheritance in this case, but wrapping the object you with to extend is fine as well. In fact, the technique is useful enough to have a name: the Decorator Pattern.

The usual way to forward all calls in Python is not to mess around with __dict__, but to override __getattr__ ("explicit is better than implicit"):

class A(object):
    def __init__(self, *args, **kwargs):
        self._b = B(*args, **kwargs)

    def __getattr__(self, name):
        return getattr(self._b, name)

__getattr__ only fires when the name is not found the usual way, so you are free to add or override names in A which you do not want to be forwarded to B.


问:
Would you use C, today, for a software project?
If yes, where and why would you use it?

If no, please provide an explanation to why C is not acceptable to you.

答: Embedded systems frequently have no more than a few kilobytes of RAM and perhaps a couple dozen kilobytes of flash, with a processor clock rate of a few MHz. C is the only option that makes any sense in such a bare-metal environment.</p>


答:
The dry, harsh truth?

Documentation is not made because projects can do without it.

Even open source projects often face stiff competition. Most of such projects don't start with large shoulders, they start off a bright idea, often a one man bright idea.

As such, they can't afford the time and costs of hiring human documentors, even if they offered to cooperate for free. A documented project, infact, has usually gone through several beginning iterations first. It often starts with 1-3, maybe 5 guys writing their novel idea down and showing it to the world as a proof of concept. If the idea proves good then "followers" may add, they tend to start asking for extensions, new options, translations... At this point the code is still a prototype, usually with hard coded options and messages.

Not all open source projects go beyond this phase, only those that break the "critical mass" needed to attract public interest. Moreover, one of the beginning developers has to "think big and far" and plan for expansions and so on. He might as well become the project "evangelist" and sometimes also "project manager" (other times it's different people). That's a necessary step to bring the project up, from proof of concept to an industry established reality.

Even then, the project manager may opt to not create documentation.

A dynamic, growing project would be both slowed down and documentation would really lag behind the code while it's being enhanced really hard, to implement translations, options, plug in managers...

What usually happens is:

A brief introductory document is made, about what the project is and where it's going to (the famous "roadmap").

If possible, an API is developed and that one is elected as "documented code" over the bulk of the underlying code.

Expecially the API but also the other code are reformatted and "PHPdoc" / "Javadoc" etc. special comments are added. They offer a decent compromise between time spent and reward: even a modest programmer usually knows how to write an one liner describing his functions, parameters get "auto" documented as well and the whole is tied to its pertaining code and thus they avoid documentation "desyncing" and lagging behing development.

Most often, a forum gets created. It's a powerful social media where end users and programmers may talk each other (and between their peers, possibly in "devs only" subforums). This allows a lot of knowledge to slowly emerge and getting consolidated by community made (read: not weighing on the developers team) FAQs and HOWTOs.

In really large projects, a wiki is also produced. I state "large projects" because they are often those with enough followers to create a wiki (a dev does) and then actually fill it beyond the "bare bones" (the community does).