答:
There is a lot of valid approaches to solve your problem.  Basile Starynkevitch proposed a “zero-bureaucracy” approach which leaves you with a simple interface and relies on the programmer using appropriately the interface.  While I like this approach, I will present another one which has more eingineering but allows the compiler to catch some errors.

Identify the various states your device can be in, as Uninitialised,
Started, Configured and  so on.  The list has to be finite.¹

For each state, define a struct holding the necessary additional
information relevant to that state, e.g. DeviceUninitialised,
DeviceStarted and so on.

Pack all treatments in one object DeviceStrategy where methods use
structures defined in 2. as inputs and outputs.  Thus, you may have
a DeviceStarted DeviceStrategy::start (DeviceUninitalised dev) method
(or whatever the equivalent might be according to your project conventions).

With this approach, a valid program must call some methods in the sequence enforced by the method prototypes.

The various states are unrelated objects, this is because of the substitution principle.  If it is useful to you to have these structures share a common ancestor, recall that the visitor pattern can be used to recover the concrete type of the instance of an abstract class.

While I described in 3. a unique DeviceStrategy class, there is situations where you may want to split the functionality it provides across several classes.

To summarise them, the key points of the design I described are:

Because of the substitution principle, objects representing device states
should be distinct and not have special inheritance relations.

Pack device treatments in startegy objects rather than in the objects
representing devices themselves, so that each device or device state
sees only itself, and the strategy sees all of them and express possible
transitions between them.

I would swear I saw once a description of a telnet client implementation
following these lines, but I was not able to find it again. It would have
been a very useful reference!

¹: For this, either follow your intuition or find the equivalence classes of methods in your actual implementation for the relation “method₁ ~ method₂ iff. it is valid to use them on the same object” — assuming you have a big object encapsulating all the treatments on your device.  Both methods of listing states give fantastic results.


问:
Is there a pattern or best practice for passing a reference type to multiple classes vs a static class?
My .NET application creates HTML files, and as such, the structure looks like

```<code>variable myData
BuildHomePage()
variable graph = new BuildGraphPage(myData)
variable table = BuildTablePage(myData)
</code>```

BuildGraphPage and BuildTablePage both require access data, the myData object.

In the above example, I've passed the myData object to 2 constructors. This is what I'm doing now, in my current project.

The myData object, and it's properties are all readonly.

The problem is, the number of pages which will require this object has grown. In the real project, there are currently 4, but the new spec is to have about 20. Passing this object to the constructor of each new object and assigning it to a field is a little time consuming, but not a hardship!

This poses the question whether it's better practice to continue as I have, or to refactor and create a new static class for myData which can be referenced from any where in my project.

I guess my abilities to use Google are poor, because I did try and find an appropriate pattern as I am sure this type of design must be common place but my results returned nothing.

Is there a pattern which is suited, or do best practices lean towards one implementation over another.

答: It's fine to put immutable data in a static class, especially if the values truly are constants (say, the speed of light, or pi) or you think you'll never need to change it (e.g. for testing different configurations). If the data is mutable, making it accessible from anywhere in the code is the worst thing you can do; it becomes a global variable and you'll create invisible dependencies between every piece of code that accesses it. You should limit the scope of mutable data as much as possible and explicitly pass it around where it's needed so the dependencies are visible and obvious.</p>

ContentLicense: CC BY-SA 3.0


问:
Interface design where functions need to be called in a specific sequence
The task is to configure a piece of hardware within the device, according to some input specification. This should be achieved as follows:

1) Collect the configuration information. This can happen at different times and places. For example, module A and module B can both request (at different times) some resources from my module. Those 'resources' are actually what the configuration is.

2) After it is clear that no more requests are going to be realized, a startup command, giving a summary of the requested resources, needs to be sent to the hardware.

3) Only after that, can (and must) detailed configuration of said resources be done.

4) Also, only after 2), can (and must) routing of selected resources to the declared callers be done.

A common cause for bugs, even for me, who wrote the thing, is mistaking this order. What naming conventions, designs or mechanisms can I employ to make the interface usable by someone who sees the code for the first time?

答:
Use a builder-pattern.

Have an object which has methods for all the operations you mentioned above. However, it doesn't perform these operations right away. It just remembers each operation for later. Because the operations aren't executed right away, the order in which you pass them to the builder doesn't matter.

After you defined all the operations on the builder, you call an execute-method. When this method is called, it performs all the steps you listed above in the correct order with the operations you stored above. This method is also a good place to perform some operation-spanning sanity-checks (like trying to configure a resource which wasn't set up yet) before writing them to the hardware. This might save you from damaging the hardware with a nonsensical configuration (in case your hardware is susceptible to this).


问:
Is client side JavaScript capable of replicating the Node.JS module loading system?
I like the Node.JS style of JavaScript, where I can write all of my functionalities into smaller files and then require those neatly from within my code. I'm even thinking about trying to write a framework to mimic that behavior in client-side JS.

My goal would be to implement the module loading system as accurately as possible - See Module docs.

For require(), I can use things detailed in answers to this question, most notably JQuery's $.getScript(). It seems to me that other aspects of the module loading system should be possible as well.

So I'm asking more experienced programmers here first, before I waist my time: Is there something that I'm missing that's going to cause such an attempt to fail miserably, or can  this be successfully done?

答:
The concept you are looking for is called AMD which stand for Asynchronous Module Definition

The Asynchronous Module Definition (AMD) API specifies a mechanism for defining modules such >that the module and its dependencies can be asynchronously loaded. This is particularly well >suited for the browser environment where synchronous loading of modules incurs performance, >usability, debugging, and cross-domain access problems.

Full specification

As mentionend in the comments there are multiple libraries for doing this. You can find a pretty complete comparison of all available frameworks here


答:
```<code>public class Executor {

private Executor() {} // helper class

  public void execute(MyStepsRunnable r) {
    r.step1();
    r.step2();
    r.step3();
  }
}

interface MyStepsRunnable {

  void step1();
  void step2();
  void step3();
}
</code>```

Using this pattern you are sure that any implementor will execute in this exact order. You can go one step further and make an ExecutorFactory which will build Executors with custom execution paths.

Title: Interface design where functions need to be called in a specific sequence

Body:
The task is to configure a piece of hardware within the device, according to some input specification. This should be achieved as follows:

1) Collect the configuration information. This can happen at different times and places. For example, module A and module B can both request (at different times) some resources from my module. Those 'resources' are actually what the configuration is.

2) After it is clear that no more requests are going to be realized, a startup command, giving a summary of the requested resources, needs to be sent to the hardware.

3) Only after that, can (and must) detailed configuration of said resources be done.

4) Also, only after 2), can (and must) routing of selected resources to the declared callers be done.

A common cause for bugs, even for me, who wrote the thing, is mistaking this order. What naming conventions, designs or mechanisms can I employ to make the interface usable by someone who sees the code for the first time?

Body:
public class Executor {

private Executor() {} // helper class

  public void execute(MyStepsRunnable r) {
    r.step1();
    r.step2();
    r.step3();
  }
}

interface MyStepsRunnable {

  void step1();
  void step2();
  void step3();
}

Using this pattern you are sure that any implementor will execute in this exact order. You can go one step further and make an ExecutorFactory which will build Executors with custom execution paths.


问:
Macro guard in Objective-C
I have noticed that many famous libraries written in Objective-C (eg. AFNetworking) use the macro guard inside their header files.
Im aware that the #import directive, which works exactly like #include, includes each file only once, obviating the need for #include guards.
For what reason are still used?</p>

答:
Because the solution that is already there works 100%, and changing it would require effort and bear a (slight) risk of accidentally introducing defects.

Generally, replacing deprecated constructs with more modern constructs is unpopular with users, and most never do it until you force them by removing the deprecated construct. And from a business perspective they are completely right: modernizing code costs money and yields absolutely no benefit to them, so why do it? The only one profiting from it is the platform vendor, because they can make their compiler simpler, and most application programmers don't care that much about the well-being of their tool vendor.

Title: Macro guard in Objective-C


问:
Ruby on Rails application interfacing with a Datamax barcode printer
I am trying to find a standalone way to interface with a Datamax M-Class Mark2 label printer through a Ruby on Rails application. I currently have a solution that is working, which i use javascript to interface with an ActiveX object on the users machine. If at all possible i would like to accomplish this without the need for the ActiveX object.</p>

答:
Outside of browser plugins like ActiveX, this it not possible in a web application run through a browser.  Web applications are sandboxed for user safety and don't have access to the user's machine for stuff like this.

If you don't like ActiveX, you could build a solution using another plugin (Java Applet, etc) but you can't do this with native web technologies.


答:
You can have the startup method return an object that is a required parameter to the configuration:

```
Resource *MyModule::GetResource();
MySession *MyModule::Startup();
void Resource::Configure(MySession *session);
```

Even if your MySession is just an empty struct, this will enforce through type safety that no Configure() method can be called before the startup.

Body:
You can have the startup method return an object that is a required parameter to the configuration:

Resource *MyModule::GetResource();
MySession *MyModule::Startup();
void Resource::Configure(MySession *session);

Even if your MySession is just an empty struct, this will enforce through type safety that no Configure() method can be called before the startup.


答:
Building on the Answer of Cashcow - why do you have to present a new Object to the caller, when you can just present a new Interface ?
Rebrand-Pattern:

```<code>class IStartable     { public: virtual IRunnable      start()     = 0; };
class IRunnable      { public: virtual ITerminateable run()       = 0; };
class ITerminateable { public: virtual void           terminate() = 0; };
</code>```

You can also let ITerminateable implement IRunnable, if a session can be run multiple times.

Your object:

```<code>class Service : IStartable, IRunnable, ITerminateable
{
  public:
    IRunnable      start()     { ...; return this; }
    ITerminateable run()       { ...; return this; }
    void           terminate() { ...; }
}

// And use it like this:
IStartable myService = Service();

// Now you can only call start() via the interface
IRunnable configuredService = myService.start();

// Now you can also call run(), because it is wrapped in the new interface...
</code>```

In this way you can only call the right methods, since you have only the IStartable-Interface in the beginning and will get the run() Method only accessible when you have called start(); From the outside it looks like a pattern with multiple classes and Objects, but the underlying class stays one class, which is always referenced.

Body:
Building on the Answer of Cashcow - why do you have to present a new Object to the caller, when you can just present a new Interface ?
Rebrand-Pattern:

class IStartable     { public: virtual IRunnable      start()     = 0; };
class IRunnable      { public: virtual ITerminateable run()       = 0; };
class ITerminateable { public: virtual void           terminate() = 0; };

You can also let ITerminateable implement IRunnable, if a session can be run multiple times.

Your object:

class Service : IStartable, IRunnable, ITerminateable
{
  public:
    IRunnable      start()     { ...; return this; }
    ITerminateable run()       { ...; return this; }
    void           terminate() { ...; }
}

// And use it like this:
IStartable myService = Service();

// Now you can only call start() via the interface
IRunnable configuredService = myService.start();

// Now you can also call run(), because it is wrapped in the new interface...

In this way you can only call the right methods, since you have only the IStartable-Interface in the beginning and will get the run() Method only accessible when you have called start(); From the outside it looks like a pattern with multiple classes and Objects, but the underlying class stays one class, which is always referenced.


问:
What to do about "next piece syndrome"?
Inspired by this question:
What to do about "stopping point syndrome"?

I often find myself a half hour away from knocking-off time having just wrapped up a component of my work, and facing a "next piece" that is going to take more than half an hour. (That's happening right now, as a matter of fact. Hence my surfing stackexchange during business hours!)

What do you do? Launch into the new piece knowing you'll have to stop in the middle? Set it aside and twiddle your thumbs until the clock runs out?

答:
How important is the clock to your employer?

The simple answer may be to sometimes start the new task and see it through, finishing late as a result, but sometimes just leave early. So long as you're averaging out right, and getting work done on time, starting/leaving at exactly the right time shouldn't be an issue - though there are probably core hours when you are expected to be there and available to answer questions etc.

The problem is, of course, that not all employers will see it this way.

Even if no-one is watching the clock, it's probably a good idea to watch your hours yourself, though - keep yourself from sliding down a slippery slope to trouble without noticing.

ContentLicense: CC BY-SA 2.5

Title: What to do about "next piece syndrome"?


答:
No. Node.js require() is based on the Common.js module system which uses synchronous loading.

Unless you do some server-side preprocessing (bundling) to serve all scripts at once, this is impossible in the browser, where resources <s>are</s> should be loaded asynchronously. You might want to have a look at browserify.

However, there is the Asynchronous Module Definition proposal which has an async require function that takes a callback. This is widely implemented in various libraries, you probably don't have come up with your own. RequireJs is a well known one, you will find others when searching for "AMD loader".

Title: Is client side JavaScript capable of replicating the Node.JS module loading system?

Body:
I like the Node.JS style of JavaScript, where I can write all of my functionalities into smaller files and then require those neatly from within my code. I'm even thinking about trying to write a framework to mimic that behavior in client-side JS.

My goal would be to implement the module loading system as accurately as possible - See Module docs.

For require(), I can use things detailed in answers to this question, most notably JQuery's $.getScript(). It seems to me that other aspects of the module loading system should be possible as well.

So I'm asking more experienced programmers here first, before I waist my time: Is there something that I'm missing that's going to cause such an attempt to fail miserably, or can  this be successfully done?


问:
What is considered to be a "modification" of sources under the BSD license?
I have a question about the 3-clause BSD license based on its Wiki description.

It states:

Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met: ...

What is understood by "modification"?
Specifically I am interested whether any/all of the following is considered as such modification:

Reading the original sources and then re-implementing a custom way.

Reading the original sources, waiting for a year and then re-implementing something based on whatever you could remember.

Direct and very significant "complete" refactoring of the original sources.

答:
Modification in this case is anything that is a non-trivial change to the source code.

So what are some examples of trivial change?

White space only changes or other formatting such as line breaks.

Renaming variables

Renaming a file or module

Notice that the trivial changes don't do anything to the programmatic flow of the application.

Non-trivial changes would include:

Re-working algorithmic flow

Adding functionality (logging, tracing, enhancements)

Bug fixes

Notice that the non-trivial changes are additive or that they affect the program's flow.

They are some grey areas, though.  For example, refactoring a method by extracting some portions out may or may not be trivial.  It depends upon the complexity of the extraction and what needed to be re-arranged in order to support the extraction.  Likewise, extracting cut & paste blocks of code into a single method requires some analysis to determine if it's not trivial.

So let's tackle your questions.

Reading the original sources and then re-implementing a custom way.

I'm going to go with non-trivial and therefore a modification to the original code.  Key aspect here is re-implementing [in] a custom way.  It wasn't a copy & paste exercise; you had to put significant effort into implementing and validating your work.

Reading the original sources, waiting for a year and then re-implementing something based on whatever you could remember.

Hard to say, and could go either way.  "Waiting time" has nothing to do with determining whether or not the modification was trivial.  For example, you could have a photographic memory and were therefore able to re-write the code verbatim from memory.  It's an impressive feat but it wouldn't qualify as a modification.  On the other hand, you could end up with a complete re-write of the algorithms and therefore have created a non-trivial change.

Direct and very significant "complete" refactoring of the original sources.

Definitely a modification of the original code.  Complete refactoring implies re-arranging significant amounts of code and altering the program's flow.

Getting at the peripheral of your question, why would you care so much about whether or not a change counts as a modification.  If you make a non-trivial change to the code, then you own the copyright to that change.  And even though the BSD license gives you pretty much free reign to do whatever with the original project, if you re-wrote the entire project then you can lay claim to all of the copyright of the new project.

Courtesy would suggest acknowledging the earlier project as inspiration, but you're not legally obligated to do so once you've completely re-written a project.  And if you haven't completely re-written the project then you'll need to abide by the clauses of the BSD license.


问:
What is the correct way to deal with similar but independent features?
Let's say we have a feature request come in and we begin work on it, which we'll call feature-1. It introduces some new logic to the application, which we'll call logic-A and logic-B. A programmer branches from the release branch and begins work on the feature.

Soon after, we get another feature request, which we'll call feature-2. It will implement logic-A and logic-C into the application. The logic A being implemented by this feature is the same logic-A as was implemented in feature-1.

Let's also say that given logic-B, logic-A might be implemented slightly differently than it would have been given logic-C, and also differently given both logic-B and logic-C (eg. with only one feature, the code would be less flexible than with both).

How should this situation be handled?

Concrete Example (to help with any confusion in my wording)

feature-1 is a feed from programmers.stackexchange.com.

feature-2 is a feed from gaming.stackexchange.com.

logic-A is the implementation of a feed at all (assuming the application currently has no feeds), which links to the content as well and gives related information.

logic-B is that the feed's source is from programmers.stackexchange.com.

Adds to logic-A that the related programming language is displayed.

logic-C is that the feed's source is from gaming.stackexchange.com.

Adds to logic-A that the related game's name and box art is displayed.

答:
This is more a project management question then a git question.

Best is to create 2 INVEST stories:

Implements the generic logic needed for implementing feeds(logic-A). And implements the logic for whatever feed has the most value. So either logic-B or C

Implements the feed that hasn't been implemented using the generic logic in story 1. So either logic B or C

Then you plan story 1 in a sprint/release before you plan story 2. Work on story 2 can't begin until story 1 is finished so you should plan it in a release after story 1 is delivered. Story 1 is a dependency of story 2. And as such if story 1 isn't finished for whatever reason it blocks Story 2.

So if story 1 doesn't make release 1 and it gets moved to release 2. You will be forced to move story 2 to release 3. And this wil continue until story 1 is actually finished.

The reason why you have to implement the common logic in the same story. Is because upon implementing you will run in edge-cases you didn't foresee while developing the common logic.

Just building common logic first without implementing it is not INVEST because it does not add value. Working in this way increases the risk of over-engineering and adding features you aren't gonna need

If they dependency is discovered while both features are in development. Best practice is to put 1 of those features on impeded and pause the development of that feature.


问:
Requesting feedback on my OO design
I'm working on an application that creates music by itself. I'm seeking feedback for my OO design so far. This question will focus on one part of the program.

The application produces Tune objects, that are the final musical products. Tune is an abstract class with an abstract method play. It has two subclasses: SimpleTune and StructuredTune.

SimpleTune owns a Melody and a Progression (chord sequence). It's play implementation plays these two objects simultaneously. StructuredTune owns two Tune instances. It's own play plays the two Tunes one after the other according to a pattern (currently only ABAB).

Melody is an abstract class with an abstract play method. It has two subclasses: SimpleMelody and StructuredMelody.

SimpleMelody is composed of an array of notes. Invoking play on it plays these notes one after the other. StructuredMelody is composed of an array of Melody objects. Invoking play on it plays these Melodyies one after the other.

I think you're starting to see the pattern. Progression is also an abstract class with a play method and two subclasses: SimpleProgression and StructuredProgression, each composed differently and played differently.

SimpleProgression owns an array of chords and plays them sequentially. StructuredProgression owns an array of Progressions and it's play implementation plays them sequentially.

Every class has a corresponding Generator class. Tune, Melody and Progression are matched with corresponding abstract TuneGenerator, MelodyGenerator and ProgressionGenerator classes, each with an abstract generate method. For example MelodyGenerator defines an abstract Melody generate method.

Each of the generators has two subclasses, Simple and Structured. So for example MelodyGenerator has a subclasses SimpleMelodyGenerator, with an implementation of generate that returns a SimpleMelody.

(It's important to note that the generate methods encapsulate complex algorithms. They are more than mere factory method. For example SimpleProgressionGenerator.generate() implements an algorithm to compose a series of Chord objects, which are used to instantiate the returned SimpleProgression).

Every Structured generator uses another generator internally. It is a Simple generator be default, but in special cases may be a Structured generator.

Parts of this design are meant to allow the end-user through the GUI to choose what kind of music is to be created. For example the user can choose between a "simple tune" (SimpleTuneGenerator) and a "full tune" (StructuredTuneGenerator). Other parts of the system aren't subject to direct user-control.

My question regarding this design is rather specific:

When I look at my design, it looks like the design-equivalent of 'code duplication': 'class-duplication' or 'design-duplication'. You can clearly see what I'm referring to if you look at the above diagram.

My question is split into two:

Is my intuition correct? Is this duplication, or reoccuring pattern in the design, a bad thing?

If it is, how can I design this differently and more efficiently?

答:
After reading the answers posted to this question, I decided to alter my design. This is what it looks like now (simplified):

In the previous design, Melody and Progression did almost the same thing, except they were playing different elements: Notes or Chords respectively. Creating duplication.

I realized that I can improve the design by giving Note and Chord a common title: Playable. Than I can have a more general class Sequence that plays Playables.

MelodyGenerator and ProgressionGenerator then both instantiate the same kind of object, a Sequence, only they compose it with a different kind of elements: either Notes or Chords.

Also, I gave up on the recursive-tree-kind-of-thing I had in the previous design, where a StructuredMelody can hold a Melody. No more different kinds of melodies and progressions: everything is just a Sequence.

The different subclasses of MelodyGenerator and ProgressionGenerator simply implement different algorithms to produce the product Sequence.

The StructuredGenerators hold a reference to a general Generator, which means they still have the option to use another StructuredGenerator internally. Depends on them. However their default is to use a SimpleGenerator internally.

I managed to improve the design by finding the places where duplication can be eliminated by giving things a more general title: I.e. I realized Progression and Melody are practically the same thing, so I abstracted things be calling them both a Sequence.

Also, realizing the composite pattern in the melodies and progressions was unnecessary helped clear the design.

Thanks for your feedback.

Title: Requesting feedback on my OO design


问:
Is there a difference between fibers, coroutines and green threads and if that is so what is it?
Today I was reading several articles on the Internet about fibers, coroutines and green threads, and it seems like these concepts have very much in common, but there are slight differences, especially when we talk about fibers and coroutines.

Is there a concise, correct summary of what makes them different from each other?

Update: I find the Distinguishing coroutines and fibers (N4024 C++ draft) document particularly good at differentiating between fibers and coroutines.

答:
A Fiber is a lightweight thread that uses cooperative multitasking instead of preemptive multitasking.  A running fiber must explicitly "yield" to allow another fiber to run, which makes their implementation much easier than kernel or user threads.

A Coroutine is a component that generalizes a subroutine to allow multiple entry points for suspending and resuming execution at certain locations.  Unlike subroutines, coroutines can exit by calling other coroutines, which may later return to the point where they were invoked in the original coroutine.

A Green Thread is a thread that is scheduled by a virtual machine (VM) instead of natively by the underlying operating system.  Green threads emulate multithreaded environments without relying on any native OS capabilities, and they are managed in user space instead of kernel space, enabling them to work in environments that do not have native thread support.

Fibers and green threads both rely on a separate scheduler to select the next fiber or thread, but a fiber must explicitly cede control (yield) to its scheduler. A green thread will run until interrupted ("preempted") by its scheduler.

Fibers and coroutines both involve "yielding" in which the fiber/coroutine decides when to relinquish control - this is cooperative multitasking. Whereas the fiber always yields to its scheduler, a coroutine decides for itself who to yield to.

Coroutines can be used to implement fibers by always yielding to a scheduler coroutine. Fibers can be used to implement coroutines by allowing each fiber to communicate to the scheduler which fiber should be run when it yields.

ContentLicense: CC BY-SA 4.0


答:
Situations aren't always perfectly predictable, and being able to quickly adapt to changes is what this agile stuff is all about.  You want to release value for your customer as soon as possible, but that doesn't mean you need to paint yourself into a corner by creating code you know will require a redesign almost immediately.

If I were the feature-2 developer in your example, upon receiving the assignment and learning someone else was already working on something similar, I would:

Go talk to the feature-1 developer and agree on a branch where we can work on the common logic together.  This might be the branch he already created, or a separate one just for the common logic, whichever feels easier under the circumstances.

Determine what changes we need to make to the current design of the common logic in order to accommodate both features.

Determine the impact of those changes on the release date of feature-1.

If it's a minimal impact to feature-1, I would just make the common logic changes in our shared branch and move forward.

If it's a significant impact to feature-1, I would make the common logic changes in another branch, and merge it in after feature-1 is finished.  The other developer will be able to help you with this.

Another option if it's a significant impact to feature-1 is that sometimes you can make a low-impact temporary change now to make the high-impact change easier down the road.  Don't make an all-or-nothing mistake.  For example, if you isolate the display of the "extra" data like the programming language into its own function, it will be easier to make that configurable later.

Title: What is the correct way to deal with similar but independent features?

Body:
Let's say we have a feature request come in and we begin work on it, which we'll call feature-1. It introduces some new logic to the application, which we'll call logic-A and logic-B. A programmer branches from the release branch and begins work on the feature.

Soon after, we get another feature request, which we'll call feature-2. It will implement logic-A and logic-C into the application. The logic A being implemented by this feature is the same logic-A as was implemented in feature-1.

Let's also say that given logic-B, logic-A might be implemented slightly differently than it would have been given logic-C, and also differently given both logic-B and logic-C (eg. with only one feature, the code would be less flexible than with both).

How should this situation be handled?

Concrete Example (to help with any confusion in my wording)

feature-1 is a feed from programmers.stackexchange.com.

feature-2 is a feed from gaming.stackexchange.com.

logic-A is the implementation of a feed at all (assuming the application currently has no feeds), which links to the content as well and gives related information.

logic-B is that the feed's source is from programmers.stackexchange.com.

Adds to logic-A that the related programming language is displayed.

logic-C is that the feed's source is from gaming.stackexchange.com.

Adds to logic-A that the related game's name and box art is displayed.


问:
Ninject/DI: How to correctly pass initialisation data to injected type at runtime
I have the following two classes:

```<code>public class StoreService : IStoreService
{
    private IEmailService _emailService;

    public StoreService(IEmailService emailService)
    {
        _emailService = emailService;
    }
}

public class EmailService : IEmailService
{
}
</code>```

Using Ninject I can set up bindings no problem to get it to inject a concrete implementation of IEmailService into the StoreService constructor. StoreService is actually injected into the code behind of an ASP.NET WebForm as so:

```<code>[Ninject.Inject]
public IStoreService StoreService { get; set; }
</code>```

But now I need to change EmailService to accept an object that contains SMTP related settings (that are pulled from the ApplicationSettings of the Web.config). So I changed EmailService to now look like this:

```<code>public class EmailService : IEmailService
{
    private SMTPSettings _smtpSettings;

    public void SetSMTPSettings(SMTPSettings smtpSettings)
    {
        _smtpSettings = smtpSettings;
    }
}
</code>```

Setting SMTPSettings in this way also requires it to be passed into StoreService (via another public method). This has to be done in the Page_Load method in the WebForms code behind (I only have access to the Settings class in the UI layer).

With manual/poor mans DI I could pass SMTPSettings directly into the constructor of EmailService and then inject EmailService into the StoreService constructor. With Ninject I don't have access to the instances of injected types outside of the objects they are injected to, so I have to set their data AFTER Ninject has already injected them via a separate public setter method. This to me seems wrong.

How should I really be solving this scenario?

答:
With manual/poor mans DI I could pass SMTPSettings directly into the
  constructor  of EmailService and then inject EmailService into the
  StoreService constructor.

This is also what needs to happen when using Ninject, except that you don't need to inject these values into the constructors, Ninject will do it for you - it recursively resolves all dependencies you need to obtain a StoreService.

If you declare your EmailService just as you would have when using poor man's DI, like this:

```<code>public class EmailService : IEmailService
{
    private SMTPSettings _smtpSettings;

    public EmailService(SMTPSettings smtpSettings)
    {
        _smtpSettings = smtpSettings;
    }
}
</code>```

Now, when asking Ninject for a IStoreService, it will want to instantiate a StoreService.
A StoreService requires an IEmailService, so it will want to instantiate an EmailService.
An EmailService requires an SMTPSettings instance... if Ninject could be told how to obtain such an instance Ninject is able to produce a fully initialized StoreService instance.

I've never used Ninject (but I have used other .NET DI frameworks), but from what I can gather from the Ninject docs
one way to do this is to register a factory method that will produce an SMTPSettings instance (https://github.com/ninject/ninject/wiki/Providers%2C-Factory-Methods-and-the-Activation-Context):

```<code>using (IKernel kernel = new StandardKernel())
{
    kernel.Bind<SMTPSettings>()
          .ToMethod(context => new SMTPSettings() /* or any other expression that returns an SMTPSettings instance */);
}
</code>```

With this binding in place, Ninject should be able to produce a fully initialized StoreService instance.

N.B. I used http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/ to see Ninject in action, maybe it contains some useful information for you as well.

Body:
With manual/poor mans DI I could pass SMTPSettings directly into the
  constructor  of EmailService and then inject EmailService into the
  StoreService constructor.

This is also what needs to happen when using Ninject, except that you don't need to inject these values into the constructors, Ninject will do it for you - it recursively resolves all dependencies you need to obtain a StoreService.

If you declare your EmailService just as you would have when using poor man's DI, like this:

public class EmailService : IEmailService
{
    private SMTPSettings _smtpSettings;

    public EmailService(SMTPSettings smtpSettings)
    {
        _smtpSettings = smtpSettings;
    }
}

Now, when asking Ninject for a IStoreService, it will want to instantiate a StoreService.
A StoreService requires an IEmailService, so it will want to instantiate an EmailService.
An EmailService requires an SMTPSettings instance... if Ninject could be told how to obtain such an instance Ninject is able to produce a fully initialized StoreService instance.

I've never used Ninject (but I have used other .NET DI frameworks), but from what I can gather from the Ninject docs
one way to do this is to register a factory method that will produce an SMTPSettings instance (https://github.com/ninject/ninject/wiki/Providers%2C-Factory-Methods-and-the-Activation-Context):

using (IKernel kernel = new StandardKernel())
{
    kernel.Bind<SMTPSettings>()
          .ToMethod(context => new SMTPSettings() /* or any other expression that returns an SMTPSettings instance */);
}

With this binding in place, Ninject should be able to produce a fully initialized StoreService instance.

N.B. I used http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/ to see Ninject in action, maybe it contains some useful information for you as well.


问:
sell applications that run only on a GPL v2 Server
I have been testing Pentaho BI server community edition, and after reading their licensing terms I found out that the community edition is under GPLv2.

As you may know the server is intended to host different types of files and applications (like reports, olap cubes,etc...)

My question is : are we allowed to sell applications that run on the GPLv2 server ? (we will maybe modify the server source code a bit but we won't charge it to our clients. thus the modified GPL server will be just an execution environment or a container for the reports and applications that we intend to sell) ?

this suggests that our clients must install the GPL v2 edition first and then buy from us the reports that work on it but not their source code.

Thanks in advance.

答:
If your software doesn't (dynamically) link to the GPL-ed server software and runs in a separate process from the server itself, then your software is considered to be a independent work (not derived from the server) from a copyright perspective. This means that you can choose any license for your software, including a closed source one that prohibits redistribution.

If your software becomes a part of the server (for example, by being loaded as a plugin), then you must distribute your software under a license that gives the users the same rights as they get with the GPL license.  This does not forbid you from charging money for your software, but it doesn't usually make much sense, because you must provide access to your source code and your users have the right to redistribute the software.

If you make changes to the server code itself and you distribute the modified server, you must distribute that under the terms of the GPL. This is independent of the license options you have for your applications.


答:
Disclaimer: I am not a lawyer. When you make a business decision based on advise from strangers on the internet and you get sued, it's your fault.

First of all, the GPL does not forbid commercial activity. It explicitly allows you to charge for distribution. Article 4 reads:

You may charge any price or no price for each copy that you convey

That means you can modify GPL software and then charge a customer any price you want for your changed version. The catch is that you must license it to the customer as GPL, so the customer must get the sourcecode and the right to give it away to others under the same conditions. However, when your modifications are very customer-specific, there is nobody else the customer could sell these modifications to, so customization of GPL software can be a viable business model.

Now about your actual question. You write reports which are meant to be executed by a  GPL product. This is very similar in spirit to the GNU GPL FAQ "If a programming language interpreter is released under the GPL, does that mean programs written to be interpreted by it must be under GPL-compatible licenses?". The answer provided by the Free Software Foundation is this:

When the interpreter just interprets a language, the answer is no. The interpreted program, to the interpreter, is just data; a free
  software license like the GPL, based on copyright law, cannot limit
  what data you use the interpreter on. You can run it on any data
  (interpreted program), any way you like, and there are no requirements
  about licensing that data to anyone.

However, when the interpreter is extended to provide “bindings” to other facilities (often, but not necessarily, libraries), the
  interpreted program is effectively linked to the facilities it uses
  through these bindings. So if these facilities are released under the
  GPL, the interpreted program that uses them must be released in a
  GPL-compatible way. The JNI or Java Native Interface is an example of
  such a binding mechanism; libraries that are accessed in this way are
  linked dynamically with the Java programs that call them. These
  libraries are also linked with the interpreter. If the interpreter is
  linked statically with these libraries, or if it is designed to link
  dynamically with these specific libraries, then it too needs to be
  released in a GPL-compatible way.

Another similar and very common case is to provide libraries with the interpreter which are themselves interpreted. For instance, Perl
  comes with many Perl modules, and a Java implementation comes with
  many Java classes. These libraries and the programs that call them are
  always dynamically linked together.

A consequence is that if you choose to use GPL'd Perl modules or Java classes in your program, you must release the program in a
  GPL-compatible way, regardless of the license used in the Perl or Java
  interpreter that the combined Perl or Java program will run on.

So it's a tricky case which depends on technical details which are outside of my area of expertise (I have no experience with Pentaho BI server).

My final recommendation is to ask Pentaho themself for their opinion about your business model and if they consider it within their license terms or not.

Title: sell applications that run only on a GPL v2 Server

Body:
I have been testing Pentaho BI server community edition, and after reading their licensing terms I found out that the community edition is under GPLv2.

As you may know the server is intended to host different types of files and applications (like reports, olap cubes,etc...)

My question is : are we allowed to sell applications that run on the GPLv2 server ? (we will maybe modify the server source code a bit but we won't charge it to our clients. thus the modified GPL server will be just an execution environment or a container for the reports and applications that we intend to sell) ?

this suggests that our clients must install the GPL v2 edition first and then buy from us the reports that work on it but not their source code.

Thanks in advance.


问:
Am I violating LSP if the condition can be checked?
This base class for some shapes I have in my game looks like this. Some of the shapes can be resized, some of them can not.

```<code>   private Shape shape;

    public virtual void SetSizeOfShape(int x, int y)
    {
        if (CanResize()){
            shape.Width = x;
            shape.Height = y;
        }
        else {
            throw new Exception("You cannot resize this shape");
        }

    }
    public virtual bool CanResize()
    {
        return true;
    }
</code>```

In a sub class of a shape that I don't ever want to resize I am overriding the CanResize() method so a piece of client code can check before calling the SetSizeOfShape() method.

```<code>    public override bool CanResize()
    {
        return false;
    }
</code>```

Here's how it might look in my client code:

```<code>    public void DoSomething(Shape s)
    {
        if(s.CanResize()){
            s.SetSizeOfShape(50, 70);
        }
    }
</code>```

Is this violating LSP?

答:
In a nutshell, the Liskov Substitution Principle states that, given a number of objects that conform to a particular interface, you should be able to swap them without causing errors in your program.

If you can do that, then your classes don't violate LSP.

The example provided in the LSP article on Wikipedia is quite illuminating.  It says:

A typical example that violates LSP is a Square class that derives
from a Rectangle class, assuming getter and setter methods exist for
both width and height. The Square class always assumes that the width
is equal with the height. If a Square object is used in a context
where a Rectangle is expected, unexpected behavior may occur because
the dimensions of a Square cannot (or rather should not) be modified
independently.

This problem cannot be easily fixed: if we can modify
the setter methods in the Square class so that they preserve the
Square invariant (i.e., keep the dimensions equal), then these methods
will weaken (violate) the postconditions for the Rectangle setters,
which state that dimensions can be modified independently.

Violations
of LSP, like this one, may or may not be a problem in practice,
depending on the postconditions or invariants that are actually
expected by the code that uses classes violating LSP.
Mutability is a
key issue here. If Square and Rectangle had only getter methods (i.e.,
they were immutable objects), then no violation of LSP could occur.


答:
Yes. There are libraries which do this for you, like require.js or many others. When you would like to implement this yourself, you can load the sourcecode of your javascript files using XmlHttpRequest and then eval them.

However, doing this might not be the best idea from the performance point of view. Each javascript file will need to be downloaded with a separate HTTP request. This request can not happen before the script file which requested it was downloaded and executed. This can increase your page load time significantly.

But there is a workaround which allows you to work with many independent script files in development, but then deploy them as a single file in production. There are tools like Minify (which requires PHP) or YUI Compressor (which runs offline and outputs a new JS file) which can merge multiple JS files into one. As a by-effect it also reduces the size of every individual script so the overall traffic is reduced and it performs some obfuscation which discourages people (a bit) from stealing your scripts.


问:
Changing CSS classes when different strings are displayed in a text element with jQuery
I'm just wondering if this method would be possible using jQuery HTML and PHP.

Basically I have a filtering system were products are listed, some have different attribute values such as Hatchback for example.

The text element that holds these PHP echo's also have a css class that implements an icon.

I'm just wondering can I alter class's that are added to a html element just by looking at the string?

So for example if the string displays "Pick-up" then jQuery alters the class and adds the one associated with the "Pick-up" string?

Thanks sorry if this is a little confusing, I can explain more if needed.

答:
I believe it is the jQuery contains predicate you are looking for. It lets you search a string to find only nodes that contain a given string.

Assuming your items for sale have class item, this code will add various more detailed classes at runtime:

```<code>$(".item:contains('pick-up')").addClass("pickup");
$(".item:contains('hatch')").addClass('hatchback');
</code>```

Here is a live demonstration.

I have found that "searching for strings and adding CSS classes at runtime" is an effective--if not entirely elegant--way of patching "dirty data" and updating the output of code that I do not control. One ugliness to this is that the jQuery contains test is case-sensitive. So the above code would match items containing text "pick-up" but not text "Pick-up". It can be handy to use an alternate predicate that folds case (i.e. considers upper case and lower case equivalent). Here is the code that I use to add a containsfc predicate to jQuery:

```<code>// add folded-case (i.e. case insensitive) extension to jquery contains pseudo-attribute
jQuery.expr[':'].containsfc = function(a, i, m) {
  return jQuery(a).text().toUpperCase()
      .indexOf(m[3].toUpperCase()) >= 0;
};
</code>```

Then your search becomes:

```<code>$(".item:containsfc('pick-up')").addClass("pickup");
</code>```

But "dirty data" often has a lot of different variations, like the difference between "pick-up" and "pickup". So here is an even more aggressively folding predicate, that removes all non-alphabetic spaces during comparison (and folds case as well):

```<code>// add folded extension to jquery contains pseudo-attribute
// to make case-insensitive and also ignore non-alphabetic characters
jQuery.expr[':'].containsfolded = function(a, i, m) {
    return jQuery(a).text().replace(/[^A-Za-z]/g, "").toUpperCase()
    .indexOf(m[3].replace(/[^A-Za-z]/g, "").toUpperCase()) >= 0;
};
</code>```

Search then with:

```<code>$(".item:containsfolded('pick-up')").addClass("pickup");
</code>```

to match just alphabetic characters. You may salt the included replace function to taste, to keep or eliminate whatever characters you think relevant. Here is a live demo of the inclusive search function.

While this kind of string search and patch approach is imperfect, it often gets the job done, and doesn't require you to have control over the source of the data, or be responsible for its purity.

Body:
I believe it is the jQuery contains predicate you are looking for. It lets you search a string to find only nodes that contain a given string.

Assuming your items for sale have class item, this code will add various more detailed classes at runtime:

$(".item:contains('pick-up')").addClass("pickup");
$(".item:contains('hatch')").addClass('hatchback');

Here is a live demonstration.

I have found that "searching for strings and adding CSS classes at runtime" is an effective--if not entirely elegant--way of patching "dirty data" and updating the output of code that I do not control. One ugliness to this is that the jQuery contains test is case-sensitive. So the above code would match items containing text "pick-up" but not text "Pick-up". It can be handy to use an alternate predicate that folds case (i.e. considers upper case and lower case equivalent). Here is the code that I use to add a containsfc predicate to jQuery:

// add folded-case (i.e. case insensitive) extension to jquery contains pseudo-attribute
jQuery.expr[':'].containsfc = function(a, i, m) {
  return jQuery(a).text().toUpperCase()
      .indexOf(m[3].toUpperCase()) >= 0;
};

Then your search becomes:

$(".item:containsfc('pick-up')").addClass("pickup");

But "dirty data" often has a lot of different variations, like the difference between "pick-up" and "pickup". So here is an even more aggressively folding predicate, that removes all non-alphabetic spaces during comparison (and folds case as well):

// add folded extension to jquery contains pseudo-attribute
// to make case-insensitive and also ignore non-alphabetic characters
jQuery.expr[':'].containsfolded = function(a, i, m) {
    return jQuery(a).text().replace(/[^A-Za-z]/g, "").toUpperCase()
    .indexOf(m[3].replace(/[^A-Za-z]/g, "").toUpperCase()) >= 0;
};

Search then with:

$(".item:containsfolded('pick-up')").addClass("pickup");

to match just alphabetic characters. You may salt the included replace function to taste, to keep or eliminate whatever characters you think relevant. Here is a live demo of the inclusive search function.

While this kind of string search and patch approach is imperfect, it often gets the job done, and doesn't require you to have control over the source of the data, or be responsible for its purity.


答:
No, it's still substitutable, because you have the same pre-condition of requiring CanResize to be true for every class.  The problem is you are not letting the type system help you enforce that condition at compile time, and you are forcing unresizable shapes to worry about resizing APIs, which is an interface segregation violation.

Creating a separate interface for resizable shapes feels like more work now, but it will make it easier to work with in the long run, because it enables you to eliminate if (CanResize()) ... else ... code all over the place.

Title: Am I violating LSP if the condition can be checked?

Body:
This base class for some shapes I have in my game looks like this. Some of the shapes can be resized, some of them can not.

```<code>   private Shape shape;

    public virtual void SetSizeOfShape(int x, int y)
    {
        if (CanResize()){
            shape.Width = x;
            shape.Height = y;
        }
        else {
            throw new Exception("You cannot resize this shape");
        }

    }
    public virtual bool CanResize()
    {
        return true;
    }
</code>```

In a sub class of a shape that I don't ever want to resize I am overriding the CanResize() method so a piece of client code can check before calling the SetSizeOfShape() method.

```<code>    public override bool CanResize()
    {
        return false;
    }
</code>```

Here's how it might look in my client code:

```<code>    public void DoSomething(Shape s)
    {
        if(s.CanResize()){
            s.SetSizeOfShape(50, 70);
        }
    }
</code>```

Is this violating LSP?


答:
Nick, this is definitely possible with jQuery. Basically if it exist in the DOM then jQuery can manipulate it however you see fit. Here is one possible way of accomplishing this if I am understanding you correctly. Hope it helps.

```<code>var elem = $('.className').text();
if(elem === 'The text value you are looking for') {
 $(elem).removeClass().addClass('your new class name');
}
</code>```

UPDATE: Nick, Jonathans way is probably a lot cleaner. I would use his. Thanks for reminding me of this method Jonathan. :)

Title: Changing CSS classes when different strings are displayed in a text element with jQuery

Body:
I'm just wondering if this method would be possible using jQuery HTML and PHP.

Basically I have a filtering system were products are listed, some have different attribute values such as Hatchback for example.

The text element that holds these PHP echo's also have a css class that implements an icon.

I'm just wondering can I alter class's that are added to a html element just by looking at the string?

So for example if the string displays "Pick-up" then jQuery alters the class and adds the one associated with the "Pick-up" string?

Thanks sorry if this is a little confusing, I can explain more if needed.

Body:
Nick, this is definitely possible with jQuery. Basically if it exist in the DOM then jQuery can manipulate it however you see fit. Here is one possible way of accomplishing this if I am understanding you correctly. Hope it helps.

var elem = $('.className').text();
if(elem === 'The text value you are looking for') {
 $(elem).removeClass().addClass('your new class name');
}

UPDATE: Nick, Jonathans way is probably a lot cleaner. I would use his. Thanks for reminding me of this method Jonathan. :)


问:
Confused about javascript module pattern implementation
I have a class written on a project I'm working on that I've been told is using the module pattern, but it's doing things a little differently than the examples I've seen. It basically takes this form:

```<code>(function ($, document, window, undefined) {

    var module = {
        foo : bar,

        aMethod : function (arg) {
            className.bMethod(arg);
        },
        bMethod : function (arg) {
            console.log('spoons');
        }
    };
    window.ajaxTable = ajaxTable;

})(jQuery, document, window);
</code>```

I get what's going on here.
But I'm not sure how this relates to most of the definitions I've seen of the module (or revealing?) module pattern. like this one from briancray

```<code>var module = (function () {
    // private variables and functions
    var foo = 'bar';

    // constructor
    var module = function () {
    };

    // prototype
    module.prototype = {
        constructor: module,
        something: function () {
        }
    };

    // return module
    return module;
})();

var my_module = new module();
</code>```

Is the first example basically like the second except everything is in the constructor? I'm just wrapping my head around patterns and the little things at the beginnings and endings always make me not sure what I should be doing.

答:
Here is the way I implement the modular pattern when using it with jQuery, but it could be another library for you.

```<code>// IIFE - Immediately Invoked Function Expression
  (function(yourcode) {

    // The global jQuery object is passed as a parameter
    yourcode(window.jQuery, window, document);

  }(function($, window, document) {

    // The $ is now locally scoped

   // Listen for the jQuery ready event on the document
   $(function() {

     // The DOM is ready!

   });

   // The rest of the code goes here!

  }));
</code>```

Here is a great free resource from Addy Osmani on the different design patterns. Very helpful. http://addyosmani.com/resources/essentialjsdesignpatterns/book/

Body:
Here is the way I implement the modular pattern when using it with jQuery, but it could be another library for you.

// IIFE - Immediately Invoked Function Expression
  (function(yourcode) {

    // The global jQuery object is passed as a parameter
    yourcode(window.jQuery, window, document);

  }(function($, window, document) {

    // The $ is now locally scoped

   // Listen for the jQuery ready event on the document
   $(function() {

     // The DOM is ready!

   });

   // The rest of the code goes here!

  }));

Here is a great free resource from Addy Osmani on the different design patterns. Very helpful. http://addyosmani.com/resources/essentialjsdesignpatterns/book/


答:
I think that including the "canResize" you are not violating LSP because your client code works with concrete implementations that can be resized and with implementations that cannot be resized. You can switch different implementations without problem.

Another option to implement something like that is returning or not an object to perform the resizing using the maybe monad:

```<code>shape.getResizor().IfNotNull(resizor => ...)
</code>```

This its better to document your API and say "remember call first to canResize".

Body:
I think that including the "canResize" you are not violating LSP because your client code works with concrete implementations that can be resized and with implementations that cannot be resized. You can switch different implementations without problem.

Another option to implement something like that is returning or not an object to perform the resizing using the maybe monad:

shape.getResizor().IfNotNull(resizor => ...)

This its better to document your API and say "remember call first to canResize".


问:
exact answer for “what is j2ee?” - job interview
I'd like to ask if someone of you knows the exact meaning of JEE.

That's because a collegue of mine was asked this question in a job interview, and was "unable to answer properly"... to speak with his interwiewer's words. And when he told me what he said to his interviewer I got really surprised, since it was more or less what I would have answered myself - in a concise form, the first paragraph of this article.

J2EE (Java 2 Platform, Enterprise Edition) is a Java platform designed for the mainframe-scale computing typical of large enterprises. Sun Microsystems (together with industry partners such as IBM) designed J2EE to simplify application development in a thin client tiered environment. J2EE simplifies application development and decreases the need for programming and programmer training by creating standardized, reusable modular components and by enabling the tier to handle many aspects of programming automatically.

That seems not to be enough, since the interviewer asked for "more precise and less general definition".

Is there really a more precise definition for JEE? Or did my colleague just find the fussiest-interviewer-ever? :)

答:
Just say that it's a set of APIs or technologies that allows you to build secure, scalable and distributed systems. Then maybe start talking about what those are from servlets, to jsp, ORM, EJBs etc. then talk about the various frameworks. Maybe you can also say that institutions such as banks like it because it's open source, it has an established market and there are a lot of experienced developers who know it. </p>

<p>I'm assuming he/she just wanted a less "rigorous" definition of what JEE is. </p>

Body:
Just say that it's a set of APIs or technologies that allows you to build secure, scalable and distributed systems. Then maybe start talking about what those are from servlets, to jsp, ORM, EJBs etc. then talk about the various frameworks. Maybe you can also say that institutions such as banks like it because it's open source, it has an established market and there are a lot of experienced developers who know it.

I'm assuming he/she just wanted a less "rigorous" definition of what JEE is.


问:
Can unit tests verify software requirements?
I have often heard unit tests help programmers build confidence in their software.  But is it enough for verifying that software requirements are met?  I am losing confidence that software is working just because the unit tests pass.

We have experienced some failures in production deployment due to an untested\unverified execution path.  These failures are sometimes quite large, impact business operations and often requires an immediate fix.

The failure is very rarely traced back to a failing unit test.  We have large unit test bodies that have reasonable line coverage but almost all of these focus on individual classes and not on their interactions.

Manual testing seems to be ineffective because the software being worked on is typically large with many execution paths and many integration points with other software.  It is very painful to manually test all of the functionality and it never seems to flush out all the bugs.

Are we doing unit testing wrong when it seems we still are failing to verify the software correctly before deployment?  Or do most shops have another layer of automated testing in addition to unit tests?

答:
To fully test a system, you would have to put it through every possible series of input conditions, so for any non-toy system, no there's no way any testing system should be expected to catch all errors.

However, this is a case where perfection is the enemy of "good enough".  If a testing system reduces the chance of shipping a defective product, or reduces the number of shipped defects, or reduces the amount of time it takes to reasonably test a system before it ships, then it has value.

Simply having "large unit test bodies that have reasonable line coverage" is no guarantee of bug-free code.  However, it's probably a lot better than no testing system at all.

Note that unit testing is only one type of software test.  It wouldn't hurt to create a few automated integration tests either.  Not only that, when I am about to release a new version of software I always manually check that I can do a couple critical functions, just in case.


答:
In general no. For toy programs (say solutions to Project Euler problems), sure.

This is before getting into a religious discussion of what are unit tests (if it uses a file system object, is it a unit test? Let the inquisition begin!)

For N-Tier applications, where N > 1, integration tests are needed, and even they may not actually be suitable for requirements verification, as most integration tests are between two tiers, and not normally end-to end testing. Most end-to-end testing (a minimal test for most requirements) is usually done as / in conjunction with system level test.

On a large project I worked on, we had CUT (Code and Unit Test) done by the developer. The build code then went into Integration and Test (I&T), where some minor requirements that could be verified (warning alerts will be displayed in 'FUNKY_RED' in the admin console). When it passed that, it was released to System Level Test (SLT). The 'Requirements Testing' was done in SLT, where they had a mirror of the operational site. Finally, it was deployed and went to Acceptance Test.

Some of this would change, depending on the scale of the project. But in my experience, anything with more than one module/jar/library will not be sufficient with just unit tests.

Add in testing a GUI, and it gets really unlikely that a you can have 100% confidence without live interaction.

EDIT:
Looking back, I think that take away is that for complex systems, simple testing (like unit testing) is not going to be sufficient for requirements validation. Complex systems will require complex (sophisticated?) testing to verify.

Title: Can unit tests verify software requirements?

Body:
I have often heard unit tests help programmers build confidence in their software.  But is it enough for verifying that software requirements are met?  I am losing confidence that software is working just because the unit tests pass.

We have experienced some failures in production deployment due to an untested\unverified execution path.  These failures are sometimes quite large, impact business operations and often requires an immediate fix.

The failure is very rarely traced back to a failing unit test.  We have large unit test bodies that have reasonable line coverage but almost all of these focus on individual classes and not on their interactions.

Manual testing seems to be ineffective because the software being worked on is typically large with many execution paths and many integration points with other software.  It is very painful to manually test all of the functionality and it never seems to flush out all the bugs.

Are we doing unit testing wrong when it seems we still are failing to verify the software correctly before deployment?  Or do most shops have another layer of automated testing in addition to unit tests?


答:
You have several things to consider:

Requirements must be testable.  If they're not testable, then you can't verify them with tests.

Unit tests are not proof of correctness, mainly because they cannot provide 100% code coverage in any practical way.

The first bullet is fairly easy to correct, if difficult to implement in practice: make your requirements testable.  The best way to do that is to define an acceptance test at the same time that you write the requirement.

Bullet two just raises the question, "How do I write more reliable software?"  That, my friend, is the subject of a lifetime of study.

However, from a testing standpoint, you can improve the situation by adding Integration Tests and System Level Tests.  Unit tests, on their own, are often insufficient to completely describe a rigorous test suite.  Work with your stakeholders to define and write tests, the scope, cost and benefits of which everyone understands.


问:
Alternatives to multiple inheritance for my architecture (NPCs in a Realtime Strategy game)?
Coding isn't that hard actually. The hard part is to write code that makes sense, is readable and understandable. So I want to get a better developer and create some solid architecture.

So I want to do create an architecture for NPCs in a video-game. It is a Realtime Strategy game like Starcraft, Age of Empires, Command & Conquers, etc etc.. So I'll have different kinds of NPCs. A NPC can have one to many abilities (methods) of these: Build(), Farm() and Attack().

Examples:

Worker can Build() and Farm()

Warrior can Attack()

Citizen can Build(), Farm() and Attack()

Fisherman can Farm() and Attack()

I hope everything is clear so far.

So now I do have my NPC Types and their abilities. But lets come to the technical / programmatical aspect.

What would be a good programmatic architecture for my different kinds of NPCs?

Okay I could have a base class. Actually I think this is a good way to stick with the DRY principle. So I can have methods like WalkTo(x,y) in my base class since every NPC will be able to move. But now lets come to the real problem. Where do I implement my abilities? (remember: Build(), Farm() and Attack())

Since the abilities will consists of the same logic it would be annoying / break DRY principle to implement them for each NPC (Worker,Warrior, ..).

Okay I could implement the abilities within the base class. This would require some kind of logic that verifies if a NPC can use ability X. IsBuilder, CanBuild, .. I think it is clear what I want to express.

But I don't feel very well with this idea. This sounds like a bloated base class with too much functionality.

I do use C# as programming language. So multiple inheritance isn't an option here. Means: Having extra base classes like Fisherman : Farmer, Attacker won't work.

答:
Composition and Interface Inheritance are the usual alternatives to classical multiple inheritance.

Everything that you described above that starts with the word "can" is a capability that can be represented with an interface, as in ICanBuild, or ICanFarm.  You can inherit as many of those interfaces as you think you need.

```<code>public class Worker: ICanBuild, ICanFarm
{
    #region ICanBuild Implementation
    // Build
    #endregion

    #region ICanFarm Implementation
    // Farm
    #endregion
}
</code>```

You can pass in "generic" building and farming objects through the constructor of your class.  That's where composition comes in.

Body:
Composition and Interface Inheritance are the usual alternatives to classical multiple inheritance.

Everything that you described above that starts with the word "can" is a capability that can be represented with an interface, as in ICanBuild, or ICanFarm.  You can inherit as many of those interfaces as you think you need.

public class Worker: ICanBuild, ICanFarm
{
    #region ICanBuild Implementation
    // Build
    #endregion

    #region ICanFarm Implementation
    // Farm
    #endregion
}

You can pass in "generic" building and farming objects through the constructor of your class.  That's where composition comes in.


问:
Should QA file 5 separate bugs or one bug with multiple parts in it?
The question might not be as simple as it sounds, as we have struggled with this a bit.
If there are 5 separate bugs, which can be taken care of with a single fix, then it is wasteful to take this approach. One bug might slip through the cracks, and would take away from a complete picture, or just be hidden for some time (we have several years worth of outstanding bugs, and our bug tracker sucks at searching :( ).

Now, if you file a bug of 100+ parts (such as help tooltips are missing from all 234 dialogs), then it should be treated as a project and be broken down. However, if it is a bug of 3-4 parts, then the developer would attempt to fix all 3 or 4 at once. This is where it gets interesting. What if the coder only fixes 3 or 3.5 out of 4? Should after testing a new bug be filed and old one closed? If yes, then this invites sloppy programming practices, where close enough is good enough. If the bug is to fail, then all of it has to be re-done and re-tested. Now ... what if part 1 is the size of a breadbox in terms of size and risk, part 2 is more like a car, part 3 is like a house, and so on :)

When sizing and prioritizing this bug (I must mention that we use Scrum), the house part was not noticed - who reads anything but a bug title anyway? So, it was deemed a low hanging fruit - low effort, low risk, happy user = high reward. But, we got bitten with one of them recently. What seemed to be logically the same area, was actually code in transitional state, where we are trying to deprecate one method of doing things, or one library for creating widgets with another, new and better. The problem is that we had to release mid-conversion, so we made two very different beasts look alike. Our QA folks did not know that, are not expected to know that, and so in their mind these are all the same issues.

We need to be QA-friendly - not to push back too hard or too often, but also try to give a set of heuristics which would help to decide whether to file one bug or many. I suppose the problem might lie with weak tools, where splitting and merging bugs is hard to do. However, how do you deal with this stuff in general?

P.S. In Scrum - once you committed to fixing something, it probably should be fixed. Break this rule too many times and discipline will degrade.

答:
5 bugs = 5 bug reports; the fact that they can all be fixed at once is not QA's concern.

in other words, guessing that all 5 bugs stem from the same problem is putting the cart ahead of the horse.


答:
If you define interfaces like ICanBuild then your game system has to inspect every NPC by type, which is typically frowned upon in OOP.  For example: if (npc is ICanBuild).

You're better off with:

```<code>interface INPC
{
    bool CanBuild { get; }
    void Build(...);
    bool CanFarm { get; }
    void Farm(...);
    ... etc.
}
</code>```

Then:

```<code>class Worker : INPC
{
    private readonly IBuildStrategy buildStrategy;
    public Worker(IBuildStrategy buildStrategy)
    {
        this.buildStrategy = buildStrategy;
    }

    public bool CanBuild { get { return true; } }
    public void Build(...)
    {
        this.buildStrategy.Build(...);
    }
}
</code>```

...or of course you could use a number of different architectures, like some kind of domain specific language in the form of a fluent interface for defining different types of NPCs, etc., where you build NPC types by combining different behaviors:

```<code>var workerType = NPC.Builder
    .Builds(new WorkerBuildBehavior())
    .Farms(new WorkerFarmBehavior())
    .Build();

var workerFactory = new NPCFactory(workerType);

var worker = workerFactory.Build();
</code>```

The NPC builder could implement a DefaultWalkBehavior that could be overridden in the case of an NPC that flies but can't walk, etc.

Title: Alternatives to multiple inheritance for my architecture (NPCs in a Realtime Strategy game)?

Body:
Coding isn't that hard actually. The hard part is to write code that makes sense, is readable and understandable. So I want to get a better developer and create some solid architecture.

So I want to do create an architecture for NPCs in a video-game. It is a Realtime Strategy game like Starcraft, Age of Empires, Command & Conquers, etc etc.. So I'll have different kinds of NPCs. A NPC can have one to many abilities (methods) of these: Build(), Farm() and Attack().

Examples:

Worker can Build() and Farm()

Warrior can Attack()

Citizen can Build(), Farm() and Attack()

Fisherman can Farm() and Attack()

I hope everything is clear so far.

So now I do have my NPC Types and their abilities. But lets come to the technical / programmatical aspect.

What would be a good programmatic architecture for my different kinds of NPCs?

Okay I could have a base class. Actually I think this is a good way to stick with the DRY principle. So I can have methods like WalkTo(x,y) in my base class since every NPC will be able to move. But now lets come to the real problem. Where do I implement my abilities? (remember: Build(), Farm() and Attack())

Since the abilities will consists of the same logic it would be annoying / break DRY principle to implement them for each NPC (Worker,Warrior, ..).

Okay I could implement the abilities within the base class. This would require some kind of logic that verifies if a NPC can use ability X. IsBuilder, CanBuild, .. I think it is clear what I want to express.

But I don't feel very well with this idea. This sounds like a bloated base class with too much functionality.

I do use C# as programming language. So multiple inheritance isn't an option here. Means: Having extra base classes like Fisherman : Farmer, Attacker won't work.

Body:
If you define interfaces like ICanBuild then your game system has to inspect every NPC by type, which is typically frowned upon in OOP.  For example: if (npc is ICanBuild).

You're better off with:

interface INPC
{
    bool CanBuild { get; }
    void Build(...);
    bool CanFarm { get; }
    void Farm(...);
    ... etc.
}

Then:

class Worker : INPC
{
    private readonly IBuildStrategy buildStrategy;
    public Worker(IBuildStrategy buildStrategy)
    {
        this.buildStrategy = buildStrategy;
    }

    public bool CanBuild { get { return true; } }
    public void Build(...)
    {
        this.buildStrategy.Build(...);
    }
}

...or of course you could use a number of different architectures, like some kind of domain specific language in the form of a fluent interface for defining different types of NPCs, etc., where you build NPC types by combining different behaviors:

var workerType = NPC.Builder
    .Builds(new WorkerBuildBehavior())
    .Farms(new WorkerFarmBehavior())
    .Build();

var workerFactory = new NPCFactory(workerType);

var worker = workerFactory.Build();

The NPC builder could implement a DefaultWalkBehavior that could be overridden in the case of an NPC that flies but can't walk, etc.


答:
We have large unit test bodies that have reasonable line coverage but almost all of these focus on individual classes and not on their interactions.

In my experience, this is caused by poor class design, and occasionally bad unit test writing.

In an (achievable) ideal world, you unit test class A: it takes the right input and produces the right output. Then you unit test class B: it takes the right input and produces the right output. If the "right" output of class A is fed as the "right" input to class B, then it'll just work.

The only way that things go south is if your class defines some nuanced definition of "right" due to implied coupling either in data or time or sequence or... This is where good class design comes into play. By reducing your coupling and making your "right" input clearer, then there's less chance that people can screw that up.

The other thing that can happen is that your unit tests work with some naive use of "right" that doesn't test boundaries, or actually exercise your code while still getting code coverage. Bad tests will yield bad results - the worst of which will be the passing test that provides no confidence.


问:
Instantiating objects in Java
I'm learning now Java from scratch and when I started to learn about instantiating objects, I don't understand - in which cases do I need to instantiate objects?
For example I'm studying from TutsPlus course about it and there is example about "Rectangle" class. Instructor says that it needs to be instantiated.
So I started to doubt about - when do I need to instantiate those objects when writing Java code?</p>

答:
In object oriented programming, a class is a construct that defines a collection of properties and methods. It can be viewed as a template. For example, in your case  Rectangle . Then we have the instance of the class which share the common structure that the class defines. This common structure consists of the properties (may be the length, width and color) and methods (methods like; getArea(), rotate() in the above example) of the class. However, the properties of different objects are different.

Why do you need them :

Without creating objects for a class, there is no use of the class. For example , You just create a Rectangle class, there is no use of that class in your program. But when you start modelling your solution in terms of classes, You will be modelling in terms of Objects like rectangle1, rectangle2 and so on , it would be the real model of the domain that  you are working on.

Title: Instantiating objects in Java


答:
If you are coming from a background in dynamic programming languages, or new to programming generally, the new keyword can be a bit confusing, especially in languages that don't seem to always require it's use. In Java it is not uncommon to see code like this:

```<code>User user = ApplicationEnvironment.getCurrentUser();
String username = user.getName();
int maxLength = 255;
String message = new String("Current logged in user is: " + username);
</code>```

Hm, 4 variables and only one needed to be used with new? What's going on here?

The key is understanding the creation of an object vs the passing of a reference to an already existing object.

When we call new String("I'm a new string!") we are asking the computer to create a new String object in memory and hand us back a reference to it, and we usually will be assigning that reference to a variable (as we did with the last line in my example.

So why don't any of the other examples require the new key word?

Well, with the int line it's a little weird - it's a "primitive", and a primitive isn't an "object" and doesn't need the new keyword ever. It's confusing at first, but if you just remember that new only applies to objects and not primitives, you'll be ok. You can look into exactly why that is, but you'll be ok to press on if you don't understand why - just that it's how it works in Java for now.

Now, with the user and username variable the story is completely different.

What's happening is that an object has been created with the new keyword somewhere else, and we are just getting a reference to an object that some other unseen code has created for us!

So, the new keyword is when we want to tell the computer "I need an entirely new object created and saved into memory, please." When we are just assigning "references" to existing objects to different variables we don't need new!

Now, this should cause you to wonder "what exactly is a reference?" Which is precisely what a good course should explain to you later on. You'll get there if you stick with it!

For now, the rule to learn is:

If you need a NEW object, you're going to need the new keyword.

If you need a reference to an existing object - one that already
exists or that some other code will create for you - then you don't.

Title: Instantiating objects in Java

Body:
I'm learning now Java from scratch and when I started to learn about instantiating objects, I don't understand - in which cases do I need to instantiate objects?
For example I'm studying from TutsPlus course about it and there is example about "Rectangle" class. Instructor says that it needs to be instantiated.
So I started to doubt about - when do I need to instantiate those objects when writing Java code?</p>

Body:
If you are coming from a background in dynamic programming languages, or new to programming generally, the new keyword can be a bit confusing, especially in languages that don't seem to always require it's use. In Java it is not uncommon to see code like this:

User user = ApplicationEnvironment.getCurrentUser();
String username = user.getName();
int maxLength = 255;
String message = new String("Current logged in user is: " + username);

Hm, 4 variables and only one needed to be used with new? What's going on here?

The key is understanding the creation of an object vs the passing of a reference to an already existing object.

When we call new String("I'm a new string!") we are asking the computer to create a new String object in memory and hand us back a reference to it, and we usually will be assigning that reference to a variable (as we did with the last line in my example.

So why don't any of the other examples require the new key word?

Well, with the int line it's a little weird - it's a "primitive", and a primitive isn't an "object" and doesn't need the new keyword ever. It's confusing at first, but if you just remember that new only applies to objects and not primitives, you'll be ok. You can look into exactly why that is, but you'll be ok to press on if you don't understand why - just that it's how it works in Java for now.

Now, with the user and username variable the story is completely different.

What's happening is that an object has been created with the new keyword somewhere else, and we are just getting a reference to an object that some other unseen code has created for us!

So, the new keyword is when we want to tell the computer "I need an entirely new object created and saved into memory, please." When we are just assigning "references" to existing objects to different variables we don't need new!

Now, this should cause you to wonder "what exactly is a reference?" Which is precisely what a good course should explain to you later on. You'll get there if you stick with it!

For now, the rule to learn is:

If you need a NEW object, you're going to need the new keyword.

If you need a reference to an existing object - one that already
exists or that some other code will create for you - then you don't.


答:
I'd go with one bug but if the initial fix covers only part of it then the question becomes should there be a new bug opened for that portion as it could be that what was thought to be fixed at once isn't realistic or something new may be introduced and thus should be a new bug.  The key is trying to figure out where is that, "In this case let's make a new bug," line as it shouldn't be that every fix spawns a new bug but in some cases that may make sense to my mind.

My issue with 5 bug reports is that this may mean a lot of administrative overhead that isn't worthwhile as some may want each fix to be done in a separate branch which can be a bit of a waste of time to my mind.  Once there is enough experience there should be a good deal of precedence to see where that line lies.

To give a more specific example, imagine a form that has a handful of style issues,e.g. the border doesn't align properly in IE7, in Firefox another part of the form doesn't line up correctly and a few other things that are mostly cosmetic but do cause the form to not meet the specification.  Should each issue be logged as a separate bug, which could mean a lot of duplicate work for both QA and development as each bug has to be created, screen shots attached, etc. that doesn't strike me as worthwhile if bundling these together in one bug may be better all around.  This has nothing to do with knowing what is or isn't in the code, but rather how finely to slice up things.  Some people may like to slice things into itty-bitty pieces but this may be passive-aggressive if the person does it just to piss off a developer.  For example, if someone has to have their password reset to "password" would you rather have a step for typing each character one by one or is it better to assume the person knows how to type consecutive characters together so that instead of being 8 steps to enter the new password it is just one.

Title: Should QA file 5 separate bugs or one bug with multiple parts in it?

Body:
The question might not be as simple as it sounds, as we have struggled with this a bit.
If there are 5 separate bugs, which can be taken care of with a single fix, then it is wasteful to take this approach. One bug might slip through the cracks, and would take away from a complete picture, or just be hidden for some time (we have several years worth of outstanding bugs, and our bug tracker sucks at searching :( ).

Now, if you file a bug of 100+ parts (such as help tooltips are missing from all 234 dialogs), then it should be treated as a project and be broken down. However, if it is a bug of 3-4 parts, then the developer would attempt to fix all 3 or 4 at once. This is where it gets interesting. What if the coder only fixes 3 or 3.5 out of 4? Should after testing a new bug be filed and old one closed? If yes, then this invites sloppy programming practices, where close enough is good enough. If the bug is to fail, then all of it has to be re-done and re-tested. Now ... what if part 1 is the size of a breadbox in terms of size and risk, part 2 is more like a car, part 3 is like a house, and so on :)

When sizing and prioritizing this bug (I must mention that we use Scrum), the house part was not noticed - who reads anything but a bug title anyway? So, it was deemed a low hanging fruit - low effort, low risk, happy user = high reward. But, we got bitten with one of them recently. What seemed to be logically the same area, was actually code in transitional state, where we are trying to deprecate one method of doing things, or one library for creating widgets with another, new and better. The problem is that we had to release mid-conversion, so we made two very different beasts look alike. Our QA folks did not know that, are not expected to know that, and so in their mind these are all the same issues.

We need to be QA-friendly - not to push back too hard or too often, but also try to give a set of heuristics which would help to decide whether to file one bug or many. I suppose the problem might lie with weak tools, where splitting and merging bugs is hard to do. However, how do you deal with this stuff in general?

P.S. In Scrum - once you committed to fixing something, it probably should be fixed. Break this rule too many times and discipline will degrade.


答:
As other posters have mentioned a component architecture could be the solution to this problem.

```<code>class component // Some generic base component structure
{
  void update() {} // With an empty update function
}
</code>```

In this case extend the update function to implement whatever functionality the NPC should have.

```<code>class build : component
{
  override void update()
  {
    // Check if the right object is selected, resources, etc
  }
}
</code>```

Iterating a component container and updating each component allows the specific functionality of each component to be applied.

```<code>class npc
{
  void update()
  {
    foreach(component c in components)
      c.update();
  }

  list<component> components;
}
</code>```

As each type of object is wanted you could use some form of the factory pattern to construct the individual types you wanted.

```<code>npc worker;
worker.add_component<build>();
worker.add_component<walk>();
worker.add_component<attack>();
</code>```

I have always run into problems as the components get more and more complex. Keeping component complexity low (one responsibility) can help alleviate that problem.

Body:
As other posters have mentioned a component architecture could be the solution to this problem.

class component // Some generic base component structure
{
  void update() {} // With an empty update function
}

In this case extend the update function to implement whatever functionality the NPC should have.

class build : component
{
  override void update()
  {
    // Check if the right object is selected, resources, etc
  }
}

Iterating a component container and updating each component allows the specific functionality of each component to be applied.

class npc
{
  void update()
  {
    foreach(component c in components)
      c.update();
  }

  list<component> components;
}

As each type of object is wanted you could use some form of the factory pattern to construct the individual types you wanted.

npc worker;
worker.add_component<build>();
worker.add_component<walk>();
worker.add_component<attack>();

I have always run into problems as the components get more and more complex. Keeping component complexity low (one responsibility) can help alleviate that problem.


问:
Why does void in C mean not void?
In strongly-typed languages like Java and C#, void (or Void) as a return type for a method seem to mean:

This method doesn't return anything. Nothing. No return. You will not receive anything from this method.

What's really strange is that in C, void as a return type or even as a method parameter type means:

It could really be anything. You'd have to read the source code to find out.  Good luck. If it's a pointer, you should really know what you're doing.

Consider the following examples in C:

```<code>void describe(void *thing)
{
    Object *obj = thing;
    printf("%s.\n", obj->description);
}

void *move(void *location, Direction direction)
{
    void *next = NULL;

    // logic!

    return next;
}
</code>```

Obviously, the second method returns a pointer, which by definition could be anything.

Since C is older than Java and C#, why did these languages adopt void as meaning "nothing" while C used it as "nothing or anything (when a pointer)"?

答: Perhaps it would be more useful to think of void as the return type.  Then your second method would read "a method that returns an untyped pointer."

Title: Why does void in C mean not void?


答:
In C# and Java, every class is derived from an Object class. Hence whenever we wish to pass a reference to "something", we can use a reference of type Object.

Since we don't need to use void pointers for that purpose in these languages, void doesn't have to mean "something or nothing" here.

Title: Why does void in C mean not void?

Body:
In strongly-typed languages like Java and C#, void (or Void) as a return type for a method seem to mean:

This method doesn't return anything. Nothing. No return. You will not receive anything from this method.

What's really strange is that in C, void as a return type or even as a method parameter type means:

It could really be anything. You'd have to read the source code to find out.  Good luck. If it's a pointer, you should really know what you're doing.

Consider the following examples in C:

```<code>void describe(void *thing)
{
    Object *obj = thing;
    printf("%s.\n", obj->description);
}

void *move(void *location, Direction direction)
{
    void *next = NULL;

    // logic!

    return next;
}
</code>```

Obviously, the second method returns a pointer, which by definition could be anything.

Since C is older than Java and C#, why did these languages adopt void as meaning "nothing" while C used it as "nothing or anything (when a pointer)"?


答:
The keyword void (not a pointer) means "nothing" in those languages. This is consistent.

As you noted, void* means "pointer to anything" in languages that support raw pointers (C and C++). This is an unfortunate decision because as you mentioned, it does make void mean two different things.

I have not been able to find the historical reason behind reusing void to mean "nothing" and "anything" in different contexts, however C does this in several other places. For example, static has different purposes in different contexts. There is obviously precedent in the C language for reusing keywords this way, regardless of what one may think of the practice.

Java and C# are different enough to make a clean break to correct some of these issues. Java and "safe" C# also do not allow raw pointers and do not need easy C compatibility (Unsafe C# does allow pointers but the vast majority of C# code does not fall into this category). This allows them to change things up a bit without worrying about backwards compatibility. One way of doing this is introducing a class Object at the root of the hierarchy from which all classes inherit, so an Object reference serves the same function of void* without the nastiness of type issues and raw memory management.

Title: Why does void in C mean not void?


答:
void and void* are two different things.  void in C means exactly the same thing as it does in Java, an absence of a return value.  A void* is a pointer with an absence of a type.

All pointers in C need to be able to be dereferenced.  If you dereferenced a void*, what type would you expect to get?  Remember C pointers don't carry any runtime type information, so the type must be known at compile time.

Given that context, the only thing you can logically do with a dereferenced void* is ignore it, which is exactly the behavior the void type denotes.

Title: Why does void in C mean not void?