问:
What is an example of a continuation not implemented as a procedure?
An interesting discussion about the distinction between callbacks and continuations over on SO has prompted this question.  By definition, a continuation is an abstract representation of the logic needed to complete a computation.  In most languages this manifests as a one argument procedure to which you pass whatever value needs continued processing.

In a purely functional language (where all functions are pure and first class citizens), I would think a continuation could be entirely modeled as a function.  This is, after all, how I've previously understood continuations up to this point.  However, the world is full of state (sigh..) and so the general definition does not require that a continuation capture program state -- it need only encompass intent.

To help my understanding, can an example be provided in a functional language where the continuation is expressed in a more abstract way than a function?  I know Scheme allows you to grab the current continuation in a first-class manner (call/cc), but even so, it seems that the one argument procedure passed to call/cc is simply given the current continuation in the form of another one argument procedure to which the call/cc'd function can apply its result.

答:
tl;dr; The type is the overarching abstraction over a continuation

A continuation is the type of its inputs and outputs

The closest thing you will find to a non-procedure based continuation is likely the continuation monad in Haskell as it is expressed as a type, for which many functions may be used to interact with the type to interrupt, resume, backtrack, et al.

You can encapsulate that closure in a type such as the Cont type in Haskell where you get the monad abstraction as a "higher level abstraction", and there are other forms of abstraction over continuations you get when you look at the continuation as a type instead of simply a procedure, for instance

You can take two continuations and do an alternative between them if the type follows the laws to be a monoid

You can abstract over the type to change the input or output types of the continuation if you encapsulate the closure in a type that abides the laws of a functor

You can arbitrarily and partially apply or decorate your continuation with functionality such as input validation or input conversion if you encapsulate the closure in a type that follows the laws of an applicative functor

Closure vs. Procedure

At the end of the day you're basically right; a continuation is a "procedure", though I would rather refer to it as a closure. Often times continuations are best expressed as first class closures that have enclosed a bound environment. In a pure functional language you might say this is not particularly reasonable because you lack references; this is true but you can enclose values and single assignment makes enclosing the value vs. the reference the exact same thing. This gives rise to in Haskell:

```<code>(\x -> \y -> insideYIcanAccess x (and y))
</code>```

A language that lacks the ability to enclose a binding environment may technically lack first class closures, but even then there is some environment (generally the global) which is available to the closure.

So I would say it's more accurate to describe a continuation as: A closure being used in a particular way.

Conclusion

To the question of "Is a continuation implementable in any way other than a procedure?" No. If you don't have first class functions you really can't have continuations as such (yes function pointers count as first class functions, so alternatively arbitrary memory access can suffice).

Now to the question of "Are there any ways to express a continuation in a more abstract way than a procedure?" Expressing it as a type gives you a much greater abstraction, allowing you to treat the continuation in very general ways such that you can interact with the continuation in many more ways than just executing it.

Body:
tl;dr; The type is the overarching abstraction over a continuation

A continuation is the type of its inputs and outputs

The closest thing you will find to a non-procedure based continuation is likely the continuation monad in Haskell as it is expressed as a type, for which many functions may be used to interact with the type to interrupt, resume, backtrack, et al.

You can encapsulate that closure in a type such as the Cont type in Haskell where you get the monad abstraction as a "higher level abstraction", and there are other forms of abstraction over continuations you get when you look at the continuation as a type instead of simply a procedure, for instance

You can take two continuations and do an alternative between them if the type follows the laws to be a monoid

You can abstract over the type to change the input or output types of the continuation if you encapsulate the closure in a type that abides the laws of a functor

You can arbitrarily and partially apply or decorate your continuation with functionality such as input validation or input conversion if you encapsulate the closure in a type that follows the laws of an applicative functor

Closure vs. Procedure

At the end of the day you're basically right; a continuation is a "procedure", though I would rather refer to it as a closure. Often times continuations are best expressed as first class closures that have enclosed a bound environment. In a pure functional language you might say this is not particularly reasonable because you lack references; this is true but you can enclose values and single assignment makes enclosing the value vs. the reference the exact same thing. This gives rise to in Haskell:

(\x -> \y -> insideYIcanAccess x (and y))

A language that lacks the ability to enclose a binding environment may technically lack first class closures, but even then there is some environment (generally the global) which is available to the closure.

So I would say it's more accurate to describe a continuation as: A closure being used in a particular way.

Conclusion

To the question of "Is a continuation implementable in any way other than a procedure?" No. If you don't have first class functions you really can't have continuations as such (yes function pointers count as first class functions, so alternatively arbitrary memory access can suffice).

Now to the question of "Are there any ways to express a continuation in a more abstract way than a procedure?" Expressing it as a type gives you a much greater abstraction, allowing you to treat the continuation in very general ways such that you can interact with the continuation in many more ways than just executing it.


问:
Correct comment to put for boolean function arguments that are "false"?
From some open source projects, I gathered the following coding style

```<code>void someFunction(bool forget);

void ourFunction() {
  someFunction(false /* forget */);
}
</code>```

I always have doubt about what false means here. Does it mean "forget", or does the "forget" refer to its corresponding parameter (like in the case above), and "false" is meant to negate it?

What style is used most often and what is the best way (or some of the better ways) to avoid the ambiguity?

答:
This is a bizarre comment.

From the compiler's perspective, someFunction(false /* forget */); is actually someFunction(false); (the comment is stripped). So, all that line does is call someFunction with the first (and only) argument set to false.

/* forget */ is just the name of the parameter. It's probably nothing more than a quick (and dirty) reminder, that doesn't really need to be there. Just use a less ambiguous parameter name, and you won't need the comment at all.

ContentLicense: CC BY-SA 3.0


答:
Create a local boolean with a more descriptive name, and assign the value to it.  That way the meaning will be more clear.

```<code>void ourFunction() {
    bool takeAction = false;  /* false means to forget */
    someFunction( takeAction );
}
</code>```

If you can't rename the variable, then the comment should be a little more expressive:

```<code>void ourFunction() {
    /* false means that the method should forget what was requested */
    someFunction( false );
}
</code>```

Title: Correct comment to put for boolean function arguments that are "false"?

Body:
From some open source projects, I gathered the following coding style

```<code>void someFunction(bool forget);

void ourFunction() {
  someFunction(false /* forget */);
}
</code>```

I always have doubt about what false means here. Does it mean "forget", or does the "forget" refer to its corresponding parameter (like in the case above), and "false" is meant to negate it?

What style is used most often and what is the best way (or some of the better ways) to avoid the ambiguity?

Body:
Create a local boolean with a more descriptive name, and assign the value to it.  That way the meaning will be more clear.

void ourFunction() {
    bool takeAction = false;  /* false means to forget */
    someFunction( takeAction );
}

If you can't rename the variable, then the comment should be a little more expressive:

void ourFunction() {
    /* false means that the method should forget what was requested */
    someFunction( false );
}


答:
Rename the variable so a bool value makes sense.

This a million times better than adding a comment to explain arguments to a function because the name is ambiguous.


答:
In layman's words:

false is a literal.

you are passing a literal false

you are telling someFunction to not forget

you are telling someFunction that the parameter forget is false

you are telling someFunction to remember

In my opinion it would be better if the function was like this:

```<code>void someFunction(bool remember);
</code>```

the you can call it

```<code>void ourFunction() {
  someFunction(true);
}
</code>```

or keep the old name but change your wrapper function to

```<code>void ourFunctionWithRemember() {
  someFunction(false);
}
</code>```

EDIT:

As @Vorac stated, always strive to use positive words. Double negation is confusing.

Body:
In layman's words:

false is a literal.

you are passing a literal false

you are telling someFunction to not forget

you are telling someFunction that the parameter forget is false

you are telling someFunction to remember

In my opinion it would be better if the function was like this:

void someFunction(bool remember);

the you can call it

void ourFunction() {
  someFunction(true);
}

or keep the old name but change your wrapper function to

void ourFunctionWithRemember() {
  someFunction(false);
}

EDIT:

As @Vorac stated, always strive to use positive words. Double negation is confusing.


答:
The parameter may be well-named; it's hard to tell without knowing the name of the function. I assume that the comment was written by the original author of the function, and it was a reminder of what passing false into someFunction means, but for anyone coming along afterward, it's a little unclear at first glance.

Using a positive variable name (suggested in Code Complete) may be the simplest change that would make this snippet easier to read, e.g.

```<code>void someFunction(boolean remember);
</code>```

then ourFunction becomes:

```<code>void ourFunction() {
    someFunction(true /* remember */);
}
</code>```

However, using an enum makes the function call even easier to understand, at the expense of some supporting code:

```<code>public enum RememberFoo {
    REMEMBER,
    FORGET
}

...

void someFunction(RememberFoo remember);

...

void ourFunction() {
    someFunction(RememberFoo.REMEMBER);
}
</code>```

If you're unable to change the signature of someFunction for whatever reason, using a temporary variable makes the code easier to read as well, sort of like simplifying conditionals by introducing a variable for no other reason than to make the code easier to parse by humans.

```<code>void someFunction(boolean remember);

...

void ourFunction() {
    boolean remember = false;
    someFunction(remember);
}
</code>```

Body:
The parameter may be well-named; it's hard to tell without knowing the name of the function. I assume that the comment was written by the original author of the function, and it was a reminder of what passing false into someFunction means, but for anyone coming along afterward, it's a little unclear at first glance.

Using a positive variable name (suggested in Code Complete) may be the simplest change that would make this snippet easier to read, e.g.

void someFunction(boolean remember);

then ourFunction becomes:

void ourFunction() {
    someFunction(true /* remember */);
}

However, using an enum makes the function call even easier to understand, at the expense of some supporting code:

public enum RememberFoo {
    REMEMBER,
    FORGET
}

...

void someFunction(RememberFoo remember);

...

void ourFunction() {
    someFunction(RememberFoo.REMEMBER);
}

If you're unable to change the signature of someFunction for whatever reason, using a temporary variable makes the code easier to read as well, sort of like simplifying conditionals by introducing a variable for no other reason than to make the code easier to parse by humans.

void someFunction(boolean remember);

...

void ourFunction() {
    boolean remember = false;
    someFunction(remember);
}


答:
In the sample code you posted, it looks like forget is a flag argument. (I cannot be certain because the function is purely hypothetical.)

Flag arguments are a code smell. They indicate that a function does more than one thing, and a good function should do only one thing.

To avoid the flag argument, break up the function into two functions that explain the difference in the function name.

Flag argument

```<code>serveIceCream(bool lowFat)
</code>```

No flag argument

```<code>serveTraditionalIceCream()
serveLowFatIceCream()
</code>```

edit: Ideally, you don't need to keep around a function with the flag parameter at all. There are cases along the lines of what Fowler calls a tangled implementation where completely separating the functions creates duplicated code. However, the higher the cyclomatic complexity of the parameterized function, the stronger is the argument for getting rid of it.

This is only a hunch, but a parameter named forget sounds like feature envy. Why would a caller tell another object to forget something? There may be a bigger design issue.

Body:
In the sample code you posted, it looks like forget is a flag argument. (I cannot be certain because the function is purely hypothetical.)

Flag arguments are a code smell. They indicate that a function does more than one thing, and a good function should do only one thing.

To avoid the flag argument, break up the function into two functions that explain the difference in the function name.

Flag argument

serveIceCream(bool lowFat)

No flag argument

serveTraditionalIceCream()
serveLowFatIceCream()

edit: Ideally, you don't need to keep around a function with the flag parameter at all. There are cases along the lines of what Fowler calls a tangled implementation where completely separating the functions creates duplicated code. However, the higher the cyclomatic complexity of the parameterized function, the stronger is the argument for getting rid of it.

This is only a hunch, but a parameter named forget sounds like feature envy. Why would a caller tell another object to forget something? There may be a bigger design issue.


问:
Is it appropriate for interviewers to ask candidates for their Stack Exchange user name?
Would you consider it appropriate if you were asked for your Stack Exchange username in a software job interview (or as a pre-interview screening question)?

To me, it seems like a very reasonable request, and one that would be extremely informative -- I'm sure I could learn more about a candidate in five minutes by looking at the questions and answers they have posted on Stack Exchange than by a 30 minute interview. But would such a question be bad form? Is it "too personal"?

(Likewise for GitHub, or other public/online code sharing forums.)

答:
I will typically search for a candidate's information on Stack Overflow before I conduct the interview. It is public information after all, and then usually during an interview I will ask them what kinds of resources they use to learn something new, or solve a problem that they're having trouble with. If the person mentions Stack Overflow, bonus points to them, but it's not necessarily a deal breaker.

Most of my questions are open-ended and revolve around problem-solving and approaches to requirements, and they are never a question that could be answered by reading online documentation, so I'm looking for people who are always learning and exploring.

As for GitHub, I do also ask if they participate in any open-source projects, and if they mention GitHub, I consider that a bonus as well.


问:
What would the general design for an XSD to C# class converter look like?
I am looking to create a simple code generator to convert XSD definitions to C# classes.  This is partly as a learning exercise, but I would also like to get some practical use out of it eventually.

What would the general design of such an application look like?  I assume that I will need to use one of the XML parsers in the .NET framework, but which one? And what will the resulting data structure look like?  Will it be an expression tree?

From there, what happens?  Do I generate code by concatenating strings, or are there better, more sophisticated ways to do it?

Important:  I'm not looking for someone to write code for me (although very brief code samples are welcome, if they are applicable), and I don't need someone to do the research for me.  I'm perfectly capable of reading about parsers, expression trees and code generators myself.  I just need someone to help me with the broad brush strokes, so that I don't walk into too many blind alleys.

I'm also aware of open source projects like XSD2Code, but I'd rather make the attempt myself first, for learning reasons, and because the resulting tool is likely to be highly specific to my particular scenario.

答:
People use ASTs basically because a general parsing algorithm (such as a parser generator might employ) can't do any better, not because an AST is a fantastically convenient semantic model.

In your case, other people have conveniently written both a parser and some basic degree of a semantic model as part of the XML parser implementation.  So you definitely want to start there.

To me it seems like the biggest decision is whether to generate the code directly from the XML DOM, or whether to create your own semantic model and populate that from the DOM, then generate C# code from there.  The intermediate step is more work and more complexity, but probably scales better if you plan to eventually add a lot of options about exactly what gets code generated.  I suppose in theory the intermediate step would make it somewhat easier to support a format other than XSD, but that seems a far-fetched use case.

As far as what to use to generate the code, I've tried using the System.CodeDom classes to build up code programatically in a syntax-independent way - and I hated it.  For most situations it's far easier to build up a code string and just tell it to compile the string.  I can imagine a situation where your Code Generation code needed to make changes that caused ripple effects throughout the string you were generating to the point where building a string was the more difficult path, but I've never encountered it - and I like using code generation.


答:
There is a good article that mentions this exact situation as it refers to Qt-Style APIs. There, it's called The Boolean Parameter Trap and it's worth a read.

The gist of it is:

Overloading the function so that the bool isn't needed is better

Using an enum (as Esailija suggests) is best


答:
One of advices of Clean code is to minimize number of unnecessary comments1 (because they tend to rot), and to name functions and methods properly.

Following that, I would just remove the comment. After all, modern IDEs (like eclipse) pop a box with code when you put a mouse over the function. Seeing the code should clear the ambiguity.

1 Commenting some complex code is ok.


答:
To belabor the obvious, comments can lie. Thus is always better to make your code self-documenting without resorting to comments to explain, because some person (perhaps you) will change true to false and not update the comment.

If you can't change the API, then I resort to 2 options

Change the comment so that it always true, regardless of the code. If you only call this once, this is a good solution, since it keeps the documention local.

```
     someFunction( false /* true=forget, false=remember */);`
```

Use #defines, especially if you call it more than once.

```
     #define FORGET   true
     #define REMEMBER false
     someFunction(REMEMBER);
```

Body:
To belabor the obvious, comments can lie. Thus is always better to make your code self-documenting without resorting to comments to explain, because some person (perhaps you) will change true to false and not update the comment.

If you can't change the API, then I resort to 2 options

Change the comment so that it always true, regardless of the code. If you only call this once, this is a good solution, since it keeps the documention local.

     someFunction( false /* true=forget, false=remember */);`

Use #defines, especially if you call it more than once.

     #define FORGET   true
     #define REMEMBER false
     someFunction(REMEMBER);


问:
Functional Programming - Does Knowing It Help Job Prospects?
The main language that I use at the moment is C# and I am the most comfortable with it. However, I have started dabbling in F# and Haskell and really enjoy those langauges. I would love to improve my skills in either of those languages over time since it truly is fun for me to use them (as opposed to Ruby, which is hyped as "fun", I just don't get where the fun is, but I digress...). My question is directed at those who have hired/interviewed for programming positions (junior/mid-level): if you see a functional programming language on a resume, does it affect your opinion (whether positive or negatively) of that candidate?

My rationale for knowledge of functional programming affecting the view of a candidate is because it can show that the candidate can adapt to different methodologies and take a mulit-dimensional approach to problems rather than the "same old OO approach". (This may be off-base, please let me know if this assumption is as well!)

答: My personal view (no experience in the matter) would be that it would depend on the job you are interviewing for and if it depends on having specific experience in a language paradigm. If you're interviewing for a Java role (or C# in your case), they wouldn't hire you for your functional programming skills and vice versa. However, if you're going for a programming role and you can program multiple languages, that can only be seen as a good sign, i.e. you are a good computer scientist with a broad range of experience.</p>

ContentLicense: CC BY-SA 2.5


问:
An ideal way to decode JSON documents in C?
Assuming I have an API to consume that uses JSON as a data transmission method, what is an ideal way to decode the JSON returned by each API resource? For example, in Java I'd create a class for each API resource then initiate an object of that class and consume data from it.

for example:

```<code>class UserJson extends JsonParser
{
    public function UserJson(String document) {
    /*Initial document parsing goes here...*/
    }
//A bunch of getter methods . . . .
}
</code>```

The probably do something like this:

```<code>UserJson userJson = new UserJson(jsonString);//Initial parsing goes in the constructor
String username = userJson.getName();//Parse JSON name property then return it as a String.
</code>```

Or when using a programming language with associative arrays(i.e., hash table) the decoding process doesn't require creating a class:

(PHP)

```<code>$userJson = json_decode($jsonString);//Decode JSON as key=>value
$username = $userJson['name'];
</code>```

But, when I'm programming in procedural programming languages (C), I can't go with either method, since C is neither OOP nor supports associative arrays(by default, at least).

What is the "correct" method of parsing pre-defined JSON strings(i.e., JSON documents specified by the API provider via examples or documentation)?

The method I'm currently using is creating a file for each API resource to parse, the problem with this method is that it's basically a lousy version of the OOP method, as it looks exactly like the OOP method but doesn't provide any OOP benefits(e.g., can't pass an object of the parser, etc.).

I've been thinking about encapsulating each API resource parser file in a publicly accessed structure(pointing all functions/publicly usable variables to the structure) then accessing the parser file code from within the structure(parser.parse(), parser.getName(), etc.). As this way looks a bit better than the my current method, it still just a rip off the OOP way, isn't it?

Any suggestions for methods to parse JSON documents on procedural programming lanauges? Any comments on the methods I'm currently using(either 3 of them)?

答:
Since C is statically typed and JSON is not, and any JSON element can be a null, a number, a string, a boolean, an object, or an array, you basically have to do it as "a rip off the OOP way".  Create a record type that represents a JSON value, and has a member that's a tag indicating which type of JSON value it is, and then create "subclasses" that build on this record type.  To represent JSON well in C, you basically have to recreate OOP and polymorphism.

Anything that uses a JSON value will have to take a pointer to the base record type.  Remember that objects are always reference types, poor C++ language design choices notwithstanding, because otherwise it screws up polymorphism, and you require polymorphism to do this right.  When you find out what kind of "subclass" you're actually working with, (by checking the tag member,) you can cast your JSON Value pointer to the appropriate subclass type pointer to access the rest of the record.


问:
Could someone explain HaXe enums?
I have AS3/PHP background and some basic understaning of enums from C++. Saying shortly: I read this:

http://haxe.org/ref/enums

http://haxe.org/doc/cross/more_on_enum

And though - good heavens! What the sorcery is this???

Enum Constructors Parameters?
Enum Type Parameters??

Could someone explain with working examples (preferable on http://try.haxe.org/ ) the concept of enums in HaXe for someone coming from languages like PHP and AS3?

What I tried?

Firstly I wrote this:

```<code>enum Color3 {
    Red;
    Green;
    Blue;
    Grey( v : Int );
    Rgb( r : Int, g : Int, b : Int );
    Alpha( a : Int, col : Color3 );
}
</code>```

Then this:

```<code>Color3.Grey(5);
</code>```

And I don't know what to do with this further, and don't know where to search.

答:
HaXe enums are algebraic data types (ADTs). Your example in Haskell:

```<code>data Color3
  = Red
  | Green
  | Blue
  | Grey { v :: Int }
  | Rgb { r, g, b :: Int }
  | Alpha { a :: Int, col :: Color3 }
</code>```

In either language, this type simply expresses that a Color3 has a few possible values—red, green, or blue; a grey value; an arbitrary RGB value; or a Color3 value with an additional alpha channel. The fact that some of these constructors take extra parameters should not be alarming. It is simply a terse closed analog to the open behaviour of inheritance:

```<code>class Color3 {}

class Red : Color3 {}
class Green : Color3 {}
class Blue : Color3 {}

class Grey : Color3 {
  public var v:int;
  public function Grey(v:int) {
    this.v = v;
  }
}

class Rgb : Color3 {
  public var r:int, g:int, b:int;
  public function Rgb(r:int, g:int, b:int) {
    this.r = r;
    this.g = g;
    this.b = b;
  }
}

class Alpha : Color3 {
  public var a:int;
  public var col:Color3;
  public function Alpha(a:int, col:Color3) {
    this.a = a;
    this.col = col;
  }
}
</code>```

Here anyone can come along and add a new Color3 child class that may or may not respect the properties we want to enforce. With parameterised enums we have central control over all the constructors, and we also have pattern matching:

```<code>return switch (c) {
  case Red: 0xFF0000;
  case Green: 0x00FF00;
  case Blue: 0x0000FF;
  case Grey(v): (v << 16) | (v << 8) | v;
  case Rgb(r,g,b): (r << 16) | (g << 8) | b;
  case Alpha(a,c): (a << 24) | (toInt(c) & 0xFFFFFF);
}
</code>```

Contrast the alternative of adding a toInt() method to every subclass of Color3. It would be much more code, leading to more potential for errors.

Note that this particular example isn’t great because a few of the constructors are redundant: Rgb subsumes Red, Green, Blue, and Grey, and Alpha can be applied to a colour that already has Alpha, which may not be desirable.

Title: Could someone explain HaXe enums?

Body:
HaXe enums are algebraic data types (ADTs). Your example in Haskell:

data Color3
  = Red
  | Green
  | Blue
  | Grey { v :: Int }
  | Rgb { r, g, b :: Int }
  | Alpha { a :: Int, col :: Color3 }

In either language, this type simply expresses that a Color3 has a few possible values—red, green, or blue; a grey value; an arbitrary RGB value; or a Color3 value with an additional alpha channel. The fact that some of these constructors take extra parameters should not be alarming. It is simply a terse closed analog to the open behaviour of inheritance:

class Color3 {}

class Red : Color3 {}
class Green : Color3 {}
class Blue : Color3 {}

class Grey : Color3 {
  public var v:int;
  public function Grey(v:int) {
    this.v = v;
  }
}

class Rgb : Color3 {
  public var r:int, g:int, b:int;
  public function Rgb(r:int, g:int, b:int) {
    this.r = r;
    this.g = g;
    this.b = b;
  }
}

class Alpha : Color3 {
  public var a:int;
  public var col:Color3;
  public function Alpha(a:int, col:Color3) {
    this.a = a;
    this.col = col;
  }
}

Here anyone can come along and add a new Color3 child class that may or may not respect the properties we want to enforce. With parameterised enums we have central control over all the constructors, and we also have pattern matching:

return switch (c) {
  case Red: 0xFF0000;
  case Green: 0x00FF00;
  case Blue: 0x0000FF;
  case Grey(v): (v << 16) | (v << 8) | v;
  case Rgb(r,g,b): (r << 16) | (g << 8) | b;
  case Alpha(a,c): (a << 24) | (toInt(c) & 0xFFFFFF);
}

Contrast the alternative of adding a toInt() method to every subclass of Color3. It would be much more code, leading to more potential for errors.

Note that this particular example isn’t great because a few of the constructors are redundant: Rgb subsumes Red, Green, Blue, and Grey, and Alpha can be applied to a colour that already has Alpha, which may not be desirable.


答:
In C#, I used named parameters to make this clearer

```<code>someFunction(forget: false);
</code>```

Or enum:

```<code>enum Memory { Remember, Forget };

someFunction(Memory.Forget);
</code>```

Or overloads:

```<code>someFunctionForget();
</code>```

Or polymorphism`:

```<code>var foo = new Elephantine();

foo.someFunction();
</code>```

Body:
In C#, I used named parameters to make this clearer

someFunction(forget: false);

Or enum:

enum Memory { Remember, Forget };

someFunction(Memory.Forget);

Or overloads:

someFunctionForget();

Or polymorphism`:

var foo = new Elephantine();

foo.someFunction();


问:
Building and Debugging an IDE using the same IDE
This may be a question more suited some Programming Meta Discussions.

I was trying to delve deeper into the inner plugin management feature for QT Creator 2.x IDE provided by Digia Inc. So I effectively downloaded the source code for QT Creator and built it to debug how this functionality is implemented.

Hence I used an IDE to debug the same IDE. So my question is are there any pit-falls while doing so? Is it recommended that in such a scenario it's better to use two different IDEs (e.g. using Visual Studio to build QT Creator).

答:
It's really no different than building an application that can have multiple instances of itself.

From my experience, the biggest hangup is the persistence layer.  Whether that's a configuration file or a call to a database, apps seem to get trapped into accessing a specific persistence object in a specific way which makes it all the more difficult to have multiple instances in place.

After that, you have to be a bit intelligent in how you lay things out.  Visual indicators such as different backgrounds; title bar text; fonts; different account logins; different monitor locations; etc... all help make it clear which editor is primary / stable and which editor is in development.

It should be obvious, but this implies two separate code trees in the example you provided.  One for the primary editor which is never changed.  Another for the secondary editor which is under development.

And this approach holds up even to the extent of using the primary IDE to debug the development IDE as you mentioned in your question.  When you're debugging the debugger capabilities of an IDE, then you'll need to feed a separate application into the development editor so it has something different to debug.  In reality, that's not all that different from the tertiary project you would need to create in the secondary (development) editor in order to test the changes you made to the secondary editor.

It can be pretty easy to wrap your head around an axle with the meta aspects of building an IDE.  The key is to clearly differentiate what each project is doing.


问:
Simple task framework - building software from reusable pieces
I'm writing a web service with several APIs, and they will be sharing some of the implementation code. In order not to copy-paste, I would like to ideally implement each API call as a series of tasks, which are executed in a sequence determined by the business logic.

One obvious question is whether that's the best strategy for code reuse, or whether I can look at it in a different way. But assuming I want to go with tasks, several issues arise:

What's a good task interface to use?

How do I pass data computed in one task to another task in the sequence that might need it?

In the past, I've worked with task interfaces like:

```<code>interface Task<T, U> {
    U execute(T input);
}
</code>```

Then I also had sort of a "task context" object which had getters and setters for any kind of data my tasks needed to produce or consume, and it gets passed to all tasks. I'm aware that this suffers from a host of problems. So I wanted to figure out a better way to implement it this time around.

My current idea is to have a TaskContext object which is a type-safe heterogeneous container (as described in Effective Java). Each task can ask for an item from this container (task input), or add an item to the container (task output). That way, tasks don't need to know about each other directly, and I don't have to write a class with dozens of methods for each data item. There are, however, several drawbacks:

Each item in this TaskContext container should be a complex type that wraps around the actual item data. If task A uses a String for some purpose, and task B uses a String for something entirely different, then just storing a mapping between String.class and some object doesn't work for both tasks. The other reason is that I can't use that kind of container for generic collections directly, so they need to be wrapped in another object.

This means that, based on how many tasks I define, I would need to also define a number of classes for the task items that may be consumed or produced, which may lead to code bloat and duplication. For instance, if a task takes some Long value as input and produces another Long value as output, I would have to have two classes that simply wrap around a Long, which IMO can spiral out of control pretty quickly as the codebase evolves.

I briefly looked at workflow engine libraries, but they kind of seem like a heavy hammer for this particular nail. How would you go about writing a simple task framework with the following requirements:

Tasks should be as self-contained as possible, so they can be composed in different ways to create different workflows.

That being said, some tasks may perform expensive computations that are prerequisites for other tasks. We want to have a way of storing the results of intermediate computations done by tasks so that other tasks can use those results for free.

The task framework should be light, i.e. growing the code doesn't involve introducing many new types just to plug into the framework.

答:
pass the Data/Object as JSON between the Task.
any new Fields can be added easily which can store pre-processed results, converting to Domain Objects will be easier only </p>


问:
How to find bottlenecks in an application?
I'm building an application with lots of components, a lot of which are third-party so I only know what I can get from their documentation.

From time to time, by pure luck, I find out one of these components was pretty heavy and had an option to cache stuff.

I can't stop thinking that if I weren't lucky, one of these components would end up killing the performance of my app and I wouldn't have a clue what to do. I would end up adding more hardware like an idiot.

So how do you find these kind of bottlenecks? I mean I wouldn't have a nice report saying "this part is slow", like it happens with the database.

For example, today I found that a serializer I was using was heavy and wasn't being cached. Are there repeatable steps I could have followed to discover that the serializer was slowing things down?

答:
There are two paths to follow.

Blindly follow hunches.

Get an application profiler.

Let's look at the pros & cons.

Blindly follow hunches

This is:

Low capital cost (hunches are free)

Exceptionally easy to instrument (there isn't any instrumentation)

Relies heavily upon your programming experience to see problems

Not terribly accurate at finding issues

Great at creating rabbit holes that consume amazing amounts of time but generally don't generate much measurable improvement.  (which assumes you're measuring things)

Application Profiling

Generally has an acquisition cost; and the really good profilers can get expensive

Provides measurements of application performance.  The better ones isolate methods that

Consume the most amount of time

Have the most amount of calls

Require you to be able to instrument your application or at least manually step through use cases that are of concern.

Can flood you with too much information, so you need to understand what to look for

Depending upon how large your application, you can get away with following blind hunches and relying upon wall-clock time or throwing some DateTime calls in your code to keep track of how long execution takes.  I have personally taken some applications with 24+ hour runtimes and brought them down to 15 minutes and 1 - 2 hours using this approach.  But they were small applications and I could understand all of the code involved.

On the other hand, I have used profilers a couple of times with really large applications.  You need to be able to recreate the use cases that are of most concern, and that can be a pain.  Manually stepping through long processes can be problematic.  But I have used these tools to track background start-up processes and have been able to generate significant performance improvements for those applications.

To find some profilers, just search for "your_language + profiler" and you will likely have quite a few options to pick from.

Follow up to comments:

Mason Wheeler correctly points out that some good profilers can be inexpensive.  The functionality provided is most likely the biggest driver for cost.  In some ways, it's like any other software product - there is a correlation between cost and features.

There can be a half-way point as ChocoDeveloper pointed out.  You can build your own profiler, but this can be a significant investment of time.  And you run the risks of the blind path.  If you just know the problem is in MyModule.Foo(), then you can be oblivious to the problems in Module2.Bar().  But if you're aware of that risk, you can make sure you profile everything.

You can create a lighter-weight profiler this way by being very specific about what's measured and logged.  Some of the better profilers provide this ability too though.

Profilers can be run on production code.  It's generally not done as they do have a performance impact (as Doc Brown points out).  But if you can't recreate the performance issues anywhere else except production, then you run the profiler in production.  You have to understand the risks and potential issues it will create, but it can be done.

My initial response didn't give a lot of credit to building your own profiler.  In my experience, I have found it less expensive to go with an already existing profiler than to build my own.  Profilers aren't necessarily super, super complicated, but they are another project that you're taking on and will need to make sure is working correctly before you can trust the results.  For the organizations I have worked for, building a profiler was tangential to our core competencies so it didn't make business sense for us to do so.

Have a look at the Wikipedia article on Program Optimization if you haven't already.  Here are a few choice quotes cited in that article.

"Bottlenecks occur in surprising places, so don't try to second guess and put in a speed hack until you have proven that's where the bottleneck is." — Rob Pike

"The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet." — Michael A. Jackson

"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified" — Donald Knuth


答:
One example you might like are coroutines. For example, the Coroutines from Lua or the iterators/generators from Python or C# are similar in power to one-shot continuations (continuations that you are only allowed to call once) but the continuation is not explicitly made into a function. Instead, you have have ways to advance the coroutine to until the next "yield" statement.

For example, consider the following Python program:

```<code>def my_iterator():
   yield 1
   yield 2
   yield 3

def main():
   it = my_iterator()
   x = it.next()
   y = it.next()
   z = it.next()
   print x + y + z
</code>```

Its kind of similar to the following Javascript program with explicit callbacks:

```<code>function my_iterator()
  return function(cb1){
    cb1(1, function(cb2){
      cb2(2, function(cb3){
        cb3(3, function(cb4){
          throw "stop iteration";
        });
      });
    });
  });
}

function main(){
   var getNext1 = my_iterator();
   getNext1(function(x, getNext2){
      getNext2(function(y, getNext3){
         getNext3(function(z, getNext4){
            console.log(x + y + z);
         });
      });
   });
}
</code>```

The Javascript example is kind of noisy because each step needs to return the next continuation in addition to returning the yielded value (in the Python keeps track of the continuation inside the ite

Title: What is an example of a continuation not implemented as a procedure?

Body:
An interesting discussion about the distinction between callbacks and continuations over on SO has prompted this question.  By definition, a continuation is an abstract representation of the logic needed to complete a computation.  In most languages this manifests as a one argument procedure to which you pass whatever value needs continued processing.

In a purely functional language (where all functions are pure and first class citizens), I would think a continuation could be entirely modeled as a function.  This is, after all, how I've previously understood continuations up to this point.  However, the world is full of state (sigh..) and so the general definition does not require that a continuation capture program state -- it need only encompass intent.

To help my understanding, can an example be provided in a functional language where the continuation is expressed in a more abstract way than a function?  I know Scheme allows you to grab the current continuation in a first-class manner (call/cc), but even so, it seems that the one argument procedure passed to call/cc is simply given the current continuation in the form of another one argument procedure to which the call/cc'd function can apply its result.

Body:
One example you might like are coroutines. For example, the Coroutines from Lua or the iterators/generators from Python or C# are similar in power to one-shot continuations (continuations that you are only allowed to call once) but the continuation is not explicitly made into a function. Instead, you have have ways to advance the coroutine to until the next "yield" statement.

For example, consider the following Python program:

def my_iterator():
   yield 1
   yield 2
   yield 3

def main():
   it = my_iterator()
   x = it.next()
   y = it.next()
   z = it.next()
   print x + y + z

Its kind of similar to the following Javascript program with explicit callbacks:

function my_iterator()
  return function(cb1){
    cb1(1, function(cb2){
      cb2(2, function(cb3){
        cb3(3, function(cb4){
          throw "stop iteration";
        });
      });
    });
  });
}

function main(){
   var getNext1 = my_iterator();
   getNext1(function(x, getNext2){
      getNext2(function(y, getNext3){
         getNext3(function(z, getNext4){
            console.log(x + y + z);
         });
      });
   });
}

The Javascript example is kind of noisy because each step needs to return the next continuation in addition to returning the yielded value (in the Python keeps track of the continuation inside the ite


答:
I like the answer about making the comment always true, but while good I think it misses the fundamental problem with this code -- it is being called with a literal.

You should avoid using literals when calling methods.  Local variables, optional parameters, named parameters, enums -- how you best avoid them will depend upon the language and whats available, but do try to avoid them.  Literals have values, but they don't have meaning.


问:
Good Procedure or Function Design
This is in reference to the question posted here.  As I would judge it, the question there should be closed simply because it seems to ask why the Borland developers made one thing a function and another a procedure (function that returns a void result).

Now the example was given there of some string manipulation functions that exist in Borland Pascal or Delphi:

```<code>S2 := Copy(S1,3,2);
</code>```

Copies into S2 from S1 the 2 characters starting from the 3rd
  position.

```<code>Delete(S,3,2);
</code>```

Deletes from S the 2 characters starting from the 3rd position.

Now I thought it might be a good discussion on what would be good design decisions regarding devising these things.  I picked up a few rules of good design on what a function prototype should look like beyond the obvious (name reflects function, function result should be atomic, no extraneous variables), but are there any others that should govern a situation such as this one or others?   I really didn't see a good case in Atwood's code book where it was discussed.

Anyway, are there some good rules on how functions should be designed to work?  Barring the specious naming, would it be better to have

```<code>S2 := Delete(S1,3,2);
</code>```

as opposed to

```<code>Delete(S,3,2);
</code>```

?  Are there any other useful considerations or examples to discuss of good and bad function design?

答:
It seems to me that both styles have a place because they don't do the same thing from a semantics standpoint:

```<code>S2 := Delete(S1,3,2);
</code>```

Assignment implies that there is a subroutine that returns something that can in-fact be assigned to a variable.

```<code>Delete(S,3,2);
</code>```

Implies an in-place mutation by the subroutine without any kind of return value, thus making it a procedure, as procedures lack return values.

Generally speaking, functions should be designed so that they can be completely curried and so that they are conceivably pure. Since the second style of "function" design relies entirely on a side effect to generate its effect, I'd argue that you should only ever use the first style.

Title: Good Procedure or Function Design

Body:
It seems to me that both styles have a place because they don't do the same thing from a semantics standpoint:

S2 := Delete(S1,3,2);

Assignment implies that there is a subroutine that returns something that can in-fact be assigned to a variable.

Delete(S,3,2);

Implies an in-place mutation by the subroutine without any kind of return value, thus making it a procedure, as procedures lack return values.

Generally speaking, functions should be designed so that they can be completely curried and so that they are conceivably pure. Since the second style of "function" design relies entirely on a side effect to generate its effect, I'd argue that you should only ever use the first style.


问:
Is CType() ever the preferred option?
Is there any time CType() is the proper option over other methods? I did plenty of thinking on this myself, but wanted to put the question in hopes there would be answer to my question so I can put the question to rest in my workplace.

My idea is that CType() should never be used.  But others seem to think it's still around for something other than backward-compatibility.  So is there still a use for it?

A big problem is that many people don't seem to understand the difference between Casting and Converting.

Converting Vs Casting

This was one such line of code:

```<code>With objZipFile.GetEnumerator()
    While .MoveNext
        objZipEntry = CType(.Current, ZipEntry)
        … all this work is done with the objZipEntry
    End While
End With
</code>```

If my buddy ever reads this, he'll be like, "MY CODE!!!!" lol.  Yes, this is your code.  And as I discussed with him, .Current is an enumeration of objZipFile, but its type is ZipEntry.  So why is he "Converting" with CType(), when what he's really doing here is Casting.  He should be using DirectCast(.Current, ZipEntry).

So the proper way to Cast something is to use DirectCast().  But this isn't a discussion about DirectCast().  The point here is that CType() Should certainly not be used to Cast, it's a Conversion tool, so let's talk more about Converting.

To CType() or Not To CType(), I don't think so

In the simplistic example, I have a string "123", and I want the string to be converted to an Integer.  So many times, you see something like this:

```<code>Dim result as Integer = 0
result = CType("123", Integer)
</code>```

Great!  It Works!  Then what is the difference between that and this:

```<code>Dim result as Integer = 0
result = Integer.Parse("123")
</code>```

Well, with that exact example, the difference is that CType() took more resources to run.  If I gave you two clear drinks and told you one had a health rating of 10, and the other of 9.  You don't choose the 9 on principle that it isn't that much less healthy, you choose the dam 10.  Also, the Integer.Parse line is a couple characters of less typing.

Okay, but what if your input isn't "123"?  What if the input is "UrMom"?  I hear CType() won't break... but as far as I know, that isn't true.  CType() breaks just as much as Type.Parse().  I'd like some arguments on that.  Though an argument supporting CType()'s resilience alone isn't reason enough to use CType().

On the other hand, we have this option in the Type-Class:

```<code>Dim MyInt As Integer = 0
Dim TryInt As Integer = 0
If Integer.TryParse("54", TryInt) Then
    MyInt = TryInt
Else
    'Handle it appropriately
End If
</code>```

Not only are we parsing the data, but if it doesn't parse, we are handling it correctly.  Which is a much better option that throwing a Try/Catch around bad code and letting it break before handling its failure in the Catch/Finally.

Keep in mind, there may be multiple different ways to cast and convert, but the main purpose of this question is to prove or disprove that CType() simply shouldn't be used.

My main argument is this... The only arguments I've seen that support the use of CType() are those that say CType() won't break if passed bad data, or that CType() is better if you are unsure of the data going in.  In response to that I say Pish-Posh.  Rethink your code, place conditionals, and know what you're wanting to use the item for.  If something happens that you weren't expecting, handle it correctly.

So is there any time CType() is the proper option over other methods? Please provide examples.

答: CType is often useful when dealing with legacy code and database records -- where the "correct" field can potentially be of more than one type.  For instance a date or a date string.  Refacoring this can be time consuming and error prone, particularly when the results are from stored procedures and are also used by reports.</p>

Title: Is CType() ever the preferred option?


问:
What is a" feature envy" code and why is it considered a code smell?
This question on SO talks about  correcting what the OP thought is feature envy code. Another example where I saw this nifty phrase being quoted is in a recently given answer here in programmers.SE. Although I did drop in a comment to that answer asking for the information I thought it would of general help to programmers following Q&A to understand what is meant by the term feature-envy. Please feel free to edit additional tags if you think appropriate.

答:
Feature envy is a term used to describe a situation in which one object gets at the fields of another object in order to perform some sort of computation or make a decision, rather than asking the object to do the computation itself.

As a trivial example, consider a class representing a rectangle. The user of the rectangle may need to know its area. The programmer could expose width and height fields and then do the computation outside of the Rectangle class. Alternatively, Rectangle could keep the width and height fields private and provide a getArea method. This is arguably a better approach.

The problem with the first situation, and the reason it is considered a code smell, is because it breaks encapsulation.

As a rule of thumb, whenever you find yourself making extensive use of fields from another class to perform any sort of logic or computation, consider moving that logic to a method on the class itself.


问:
Wikipedia confusion about ExtJS
I'm looking at the wiki on ExtJS, the wiki on List of rich Internet application frameworks, and the wiki on Comparison of web application frameworks. I'm confused. The first line of the ExtJS wiki page says:

Ext JS is a pure JavaScript application framework for building interactive web applications[1] using techniques such as Ajax, DHTML and DOM scripting.

So I assume it's a web app framework.
But in the right hand side summary box it says:

Type:       JavaScript library

Is ExtJS a web app framework or a Javascript library or both? (Can it be both?)

ExtJS is also missing from the web app framework lists...

Thanks for reading

答:
I just came across this post on Inversion of Control. It says:

Inversion of Control is a key part of what makes a framework different to a library. A library is essentially a set of functions that you can call, these days usually organized into classes. Each call does some work and returns control to the client.

A framework embodies some abstract design, with more behavior built in. In order to use it you need to insert your behavior into various places in the framework either by subclassing or by plugging in your own classes. The framework's code then calls your code at these points.

I think this is the largest difference between jQuery and ExtJS; jQuery libraries are simply groups of functions that don't impose any design pattern on the user, while ExtJS 4 by design is almost impossible to code in for long without adopting MVC organization. Attempting to extensively use ExtJS like one huge jQuery library can easily lead to spaghetti code.

Title: Wikipedia confusion about ExtJS


答:
The naming should always resolve ambiguity for booleans. I always name boolean something like 'isThis' or 'shouldDoThat', for example:

```<code>void printTree(Tree tree, bool shouldPrintPretty){ ... }
</code>```

and so on. But when you are referencing someone else's code, its best to just leave comment when passing values.

Body:
The naming should always resolve ambiguity for booleans. I always name boolean something like 'isThis' or 'shouldDoThat', for example:

void printTree(Tree tree, bool shouldPrintPretty){ ... }

and so on. But when you are referencing someone else's code, its best to just leave comment when passing values.


问:
What is the best way to deploy commercial programs on Linux?
Due to the diversity of Linux distributions, it is quite common for programs to be distributed in source format together with scripts in order to assist the configure, make, make install sequence.

When it comes to commercial programs, however, distributing the source is usually simply not possible.

So if anybody wants to sell a program and deploy it to a Linux environment, what should he do? How is this normally done?

答:
It is done the same way it is done on any OS; by distributing packaged binaries.

configure; make; make install is still commonly seen in instructions for open source software because it is very portable and often allows you to install software written for generic UNIX rather than Linux specifically.  Compiling the software on the destination machine (or one similar to it) means that the compiler will use the header files (and the linker find the right libraries) tailored to the specific OS and (in the case of Linux) distrubution.  The GNU Autoconf configure scripts can detect a wide variety of variations in UNIX operating systems and try to choose the most appropriate libraries and compiler options for the system.

Compiling from source also allows the end user to choose specific optimisations, if they want.  Oh, and change the code any way they want, too (although the license may restrict how they can then redistribute it).

If you want to distribute commercial software, compile it first and distribute the result.  However, you may have to generate more than one version, depending on the complexity of your package.  You might have to create one version for Red Hat and derivates, another for Debian and derivatives etc; for each distribution, you may well have to generate different packages for the different versions still in common use (one for RHEL 5, another for RHEL6) because of incompatible libraries.  Or you might have to build one version for kernels older than a particular version, and another for versions since that, if a kernel interface important to your application has change.  You might have to build packages for each of these permutations (distribution + distribution version + kernel version).  You have to do this because binaries cannot adapt - that's what the source is for.


答:
You're doing it right.  This is an old problem - JSON's varying types and unordered presentation aspects are essentially the same as those presented by every data-markup language going back to at least SGML.

For C in particular, there are lots of options already available.  Googling "C JSON Parser" turns up many, including jsmn, which looks like it learned many of the lessons that Java processing of XML had to teach.  More directly to the point, this has been addressed on StackOverflow again and again.  And, of course Crockford's JSON.org lists 16 different C implementations of JSON.

Title: An ideal way to decode JSON documents in C?

Body:
Assuming I have an API to consume that uses JSON as a data transmission method, what is an ideal way to decode the JSON returned by each API resource? For example, in Java I'd create a class for each API resource then initiate an object of that class and consume data from it.

for example:

```<code>class UserJson extends JsonParser
{
    public function UserJson(String document) {
    /*Initial document parsing goes here...*/
    }
//A bunch of getter methods . . . .
}
</code>```

The probably do something like this:

```<code>UserJson userJson = new UserJson(jsonString);//Initial parsing goes in the constructor
String username = userJson.getName();//Parse JSON name property then return it as a String.
</code>```

Or when using a programming language with associative arrays(i.e., hash table) the decoding process doesn't require creating a class:

(PHP)

```<code>$userJson = json_decode($jsonString);//Decode JSON as key=>value
$username = $userJson['name'];
</code>```

But, when I'm programming in procedural programming languages (C), I can't go with either method, since C is neither OOP nor supports associative arrays(by default, at least).

What is the "correct" method of parsing pre-defined JSON strings(i.e., JSON documents specified by the API provider via examples or documentation)?

The method I'm currently using is creating a file for each API resource to parse, the problem with this method is that it's basically a lousy version of the OOP method, as it looks exactly like the OOP method but doesn't provide any OOP benefits(e.g., can't pass an object of the parser, etc.).

I've been thinking about encapsulating each API resource parser file in a publicly accessed structure(pointing all functions/publicly usable variables to the structure) then accessing the parser file code from within the structure(parser.parse(), parser.getName(), etc.). As this way looks a bit better than the my current method, it still just a rip off the OOP way, isn't it?

Any suggestions for methods to parse JSON documents on procedural programming lanauges? Any comments on the methods I'm currently using(either 3 of them)?


问:
Importance of data structures in modern S/W development
During 1990s when there were no advanced frameworks/paradigms available for S/W development , knowledge on data structures was critical... which I can comprehend.

But nowadays, for most of the problems (at least from Java/Android development) we can rely on an existing class to provide solution.
As such I believe, an in depth knowledge of data structures is not needed for someone who is stepping into programming now.

Is my belief right ?.

答:
You are partially right. Nowadays, only a few people need to be able to correctly and efficiently implement algorithms and a lot of tasks can be completed successfully without knowing all that much about algorithms.

On the other hand, knowing about the different algorithms that are commonly used in the kind of software you usually write and their strengths and weaknesses can also be a tremendous advantage in creating better performing software (or at least, avoiding writing complete crap) and in understanding some of the bottlenecks.


问:
A better alternative to incompatible implementations for the same interface?
I am working on a piece of code which performs a set task in several parallel environments where the behaviour of the different components in the task are similar but quite different.

This means that my implementations are quite different but they are all based on the relationships between the same interfaces, something like this:

```<code>IDataReader
   -> ContinuousDataReader
   -> ChunkedDataReader
IDataProcessor
   -> ContinuousDataProcessor
   -> ChunkedDataProcessor
IDataWriter
   -> ContinuousDataWriter
   -> ChunkedDataWriter
</code>```

So that in either environment we have an IDataReader, IDataProcessor and IDataWriter and then we can use Dependency Injection to ensure that we have the correct one of each for the current environment, so if we are working with data in chunks we use the ChunkedDataReader, ChunkedDataProcessor and ChunkedDataWriter and if we have continuous data we have the continuous versions.

However the behaviour of these classes is quite different internally and one could certainly not go from a ContinuousDataReader to the ChunkedDataReader even though they are both IDataProcessors. This feels to me as though it is incorrect ( possibly an LSP violation? ) and certainly not a theoretically correct way of working. It is almost as though the "real" interface here is the combination of all three classes. Unfortunately in the project I am working on with the deadlines we are working to, we're pretty much stuck with this design, but if we had a little more elbow room, what would be a better design approach in this kind of scenario?

答:
The internal behaviour of the various classes is not really relevant. The big question is if a ChunkedDataProcessor cares what kind of IDataReader and IDataWriter it is coupled with.

If a ChunkedDataProcessor can't work with a ContinuousDataReader, but accepts a IDataReader nonetheless, then you have a problem in your design. It could be regarded as a violation of the LSP, but in my opinion, the ChunkedDataProcessor just accepts the wrong interface.

Assuming there are components in the system that can work with either the continuous or the chunked variants without caring which one it is, I would use a design like this:

```<code>interface IDataReader;
interface IContinuousDataReader : extends IDataReader;
interface IChunkedDataReader : extends IDataReader;

class ChunkedDataReader : implements IChunkedDataReader;

class ChunkedDataProcessor {
    IChunkedDataReader reader;
    //...
};
</code>```

The IChunkedDataReader interface does not even have to add additional methods, but its existence allows you to impose additional constraints on the implementation that might not be suitable for the more generic IDataReader. In ChunkedDataProcessor you can then use those additional constraints of IChunkedDataReader.

Body:
The internal behaviour of the various classes is not really relevant. The big question is if a ChunkedDataProcessor cares what kind of IDataReader and IDataWriter it is coupled with.

If a ChunkedDataProcessor can't work with a ContinuousDataReader, but accepts a IDataReader nonetheless, then you have a problem in your design. It could be regarded as a violation of the LSP, but in my opinion, the ChunkedDataProcessor just accepts the wrong interface.

Assuming there are components in the system that can work with either the continuous or the chunked variants without caring which one it is, I would use a design like this:

interface IDataReader;
interface IContinuousDataReader : extends IDataReader;
interface IChunkedDataReader : extends IDataReader;

class ChunkedDataReader : implements IChunkedDataReader;

class ChunkedDataProcessor {
    IChunkedDataReader reader;
    //...
};

The IChunkedDataReader interface does not even have to add additional methods, but its existence allows you to impose additional constraints on the implementation that might not be suitable for the more generic IDataReader. In ChunkedDataProcessor you can then use those additional constraints of IChunkedDataReader.


答:
It's still vital to know about data structures. What collection implementation should you store your data in?  Do you want it to be Mutable or Immutable?  What BigO characteristics do you want for inserting entries, searching for entries, reading entries out?  What memory limitations are you under? Is that data structure cacheable?

I could go on and on!  Although most day to day developers do not need to write their own data structures, but understanding them and choosing the right one for the right use case is a vital as ever.

Title: Importance of data structures in modern S/W development

Body:
During 1990s when there were no advanced frameworks/paradigms available for S/W development , knowledge on data structures was critical... which I can comprehend.

But nowadays, for most of the problems (at least from Java/Android development) we can rely on an existing class to provide solution.
As such I believe, an in depth knowledge of data structures is not needed for someone who is stepping into programming now.

Is my belief right ?.


答:
For languages that support generics, that is usually an effective means of managing inheritance in parallel with one or more "categories". For example, your interface might become:

```<code>IDataReader<TData>
IDataWriter<TData>
IDataProcessor<TData>
</code>```

And then you might implement your classes as:

```<code>ChunkedDataReader : IDataReader<ChunkedData>
ChunkedDataWriter : IDataWriter<ChunkedData>
ChunkedDataProcessor : IDataProcessor<ChunkedData>
</code>```

Or you might even declare a single class implementing all of these, such as:

```<code>ChunkedDataFile : IDataReader<ChunkedData>, IDataWriter<ChunkedData>,
    IDataProcessor<ChunkedData>
</code>```

Then you could have a single dependent class along the lines of:

```<code>class Foo<TData>
{
    public Foo(IDataReader<TData>, IDataWriter<TData>, IDataProcessor<TData>) { ... }
}
</code>```

And this would force all of the instances to operate on the same kind of data at compile time.

Unfortunately, I'm guessing that this would involve considerable redesign/re-architecting in your case, because you haven't taken the time to define what "chunked data" or "continuous data" really is. That's the problem - right now you've got things in a somewhat more procedural than object-oriented style, you're naming classes after the things they do instead of the things they are. Verbs and collections of verbs are what interfaces - not classes - are for.

What you have is what's sometimes called the Anemic Domain Model. You have an important domain concept "chunked" or "continuous" data - but haven't taken the time to define what that actually is, in a standalone object. Instead, there are just a bunch of procedures (wrapped in interfaces and type-specific implementations) written around it.

If you focus more on what the data is, as opposed to what you might do to the data, then you might find a clean solution even if you don't have generics in your tool set. But personally, I can't think of a cleaner way.

Title: A better alternative to incompatible implementations for the same interface?

Body:
I am working on a piece of code which performs a set task in several parallel environments where the behaviour of the different components in the task are similar but quite different.

This means that my implementations are quite different but they are all based on the relationships between the same interfaces, something like this:

```<code>IDataReader
   -> ContinuousDataReader
   -> ChunkedDataReader
IDataProcessor
   -> ContinuousDataProcessor
   -> ChunkedDataProcessor
IDataWriter
   -> ContinuousDataWriter
   -> ChunkedDataWriter
</code>```

So that in either environment we have an IDataReader, IDataProcessor and IDataWriter and then we can use Dependency Injection to ensure that we have the correct one of each for the current environment, so if we are working with data in chunks we use the ChunkedDataReader, ChunkedDataProcessor and ChunkedDataWriter and if we have continuous data we have the continuous versions.

However the behaviour of these classes is quite different internally and one could certainly not go from a ContinuousDataReader to the ChunkedDataReader even though they are both IDataProcessors. This feels to me as though it is incorrect ( possibly an LSP violation? ) and certainly not a theoretically correct way of working. It is almost as though the "real" interface here is the combination of all three classes. Unfortunately in the project I am working on with the deadlines we are working to, we're pretty much stuck with this design, but if we had a little more elbow room, what would be a better design approach in this kind of scenario?

Body:
For languages that support generics, that is usually an effective means of managing inheritance in parallel with one or more "categories". For example, your interface might become:

IDataReader<TData>
IDataWriter<TData>
IDataProcessor<TData>

And then you might implement your classes as:

ChunkedDataReader : IDataReader<ChunkedData>
ChunkedDataWriter : IDataWriter<ChunkedData>
ChunkedDataProcessor : IDataProcessor<ChunkedData>

Or you might even declare a single class implementing all of these, such as:

ChunkedDataFile : IDataReader<ChunkedData>, IDataWriter<ChunkedData>,
    IDataProcessor<ChunkedData>

Then you could have a single dependent class along the lines of:

class Foo<TData>
{
    public Foo(IDataReader<TData>, IDataWriter<TData>, IDataProcessor<TData>) { ... }
}

And this would force all of the instances to operate on the same kind of data at compile time.

Unfortunately, I'm guessing that this would involve considerable redesign/re-architecting in your case, because you haven't taken the time to define what "chunked data" or "continuous data" really is. That's the problem - right now you've got things in a somewhat more procedural than object-oriented style, you're naming classes after the things they do instead of the things they are. Verbs and collections of verbs are what interfaces - not classes - are for.

What you have is what's sometimes called the Anemic Domain Model. You have an important domain concept "chunked" or "continuous" data - but haven't taken the time to define what that actually is, in a standalone object. Instead, there are just a bunch of procedures (wrapped in interfaces and type-specific implementations) written around it.

If you focus more on what the data is, as opposed to what you might do to the data, then you might find a clean solution even if you don't have generics in your tool set. But personally, I can't think of a cleaner way.


答:
Glen's answer is pretty accurate and comprehensive, but I'd like to throw Load Testing into the mix as well.

Profiling is difficult and sometimes expensive to do. It's essentially impossible to do in production. But worse than that, if your entire approach to performance management is based on profiling, you won't find out about these problems until it's too late.

If your team/project is managed well enough, you should have load tests, and this is of course assuming you already have all the prerequisites like Continuous Integration and Integration Tests. Good load tests don't just measure stuff, they establish a baseline so it's easy to see sudden or even gradual changes.

When you see a sudden change in the output of your load tests, you know it's due to a change you made since the last test run. And if you're running load tests every day or even every week, it's not hard at all to retrace your steps and find out which commit caused your throughput and/or latency to take a dive.

Load testing may not help you much after you discover a problem in production. But once you've got performance up to acceptable levels, you really should consider investing in a load testing solution so that you can get fast feedback on performance issues, preferably before you're entrenched in a particular architecture or product and can't easily back out.

Title: How to find bottlenecks in an application?

Body:
I'm building an application with lots of components, a lot of which are third-party so I only know what I can get from their documentation.

From time to time, by pure luck, I find out one of these components was pretty heavy and had an option to cache stuff.

I can't stop thinking that if I weren't lucky, one of these components would end up killing the performance of my app and I wouldn't have a clue what to do. I would end up adding more hardware like an idiot.

So how do you find these kind of bottlenecks? I mean I wouldn't have a nice report saying "this part is slow", like it happens with the database.

For example, today I found that a serializer I was using was heavy and wasn't being cached. Are there repeatable steps I could have followed to discover that the serializer was slowing things down?


问:
Defining and overriding open and closed intervals
I have been considering the following situation as part of documenting and interface (A) and an implementation (B) of that interface.

The interface A contains methods which involve the following two arguments:

A percentage, passed as an integer.

A name, passed as a string.

The valid values for the percentage are the closed range [0, 100]. No matter how you implement the interface, it is an error to allow a value outside this range as an input.

The name, as defined in the interface, allows any string containing [1, 100] characters. I want to document the interface in such a way that it neither requires nor disallows an implementation to support a name with more than 100 characters.

Clearly the valid range for percentage is a closed, inclusive interval. How would you refer to a range like I defined above for the number of characters in name? I can't refer to the interval as right-open, because the implementation might not support values with more than 100 characters.

答:
I don't believe there's a specific name for it, you'll probably have to write it out, e.g.:

The minimum length of name must be 1. There is no strict maximum length, but any implementation must support a maximum length of at least 100.

This is more concise, although somewhat less clear:

Any implementation must support a minimum length of name of 1 and a maximum of at least 100.

You can also write:

Any implementation must support the length of name in the range [1,x], with x >= 100 (x is chosen by the implementation).

Which is similar to your comment in the question on CS which was lost in the merge.

It might also be a good idea to add this to any / all of the above:

... and throw a YouNeedToRenameThis exception when outside this range.


问:
Mongodb array vs object
New with Mongodb, and I'm not sure what implications or benefits there are between the use of an array vs an object.

So..

As above what are the implications and benefits between the use of arrays and objects?

For example my case. The idea is to store a document with a "capture" time, and a 2000 slots of "packet" counters. I used object to store to packets see this , but apparently it seems better off to use arrays. What kind of considerations should one make to determine whether an array or object is more suitable (with example)?

答:
There is no "right" way to use MongoDB, only trade-offs. Let's take a simple example:

Option 1: Have everything in one document, and $push packets into an array

Option 2: Make a new document for each packet. Have each one point to their 'parent' object.

The trade-offs:

When searching for a packet, Option 1 will return the entire document, and not tell you where in the array your packet is.  Option 2 will return the specific packet.

Option 1 will fail over and die if you have too many packets (because of the 16MB limit on document size)

Option 1 is much faster if you always list all packets for a specific object. Option 2 requires many disk seeks to load all the packets. On modern hard drives, disk seeks are 100x slower than sequential disk reads.

Option 2 takes a little more disk space (because they all must link to their parent, instead of implicitly as in Option 1).

Option 2 has roughly constant write time, but Option 1 will have variable write time. In option 1, you are expanding an existing document when adding packets. Sometimes it won't fit and must be moved somewhere else. This can slow down the system. But if you're constantly adding packets to one document at a time, it will probably eventually be moved to the end where it can expand without being moved around, so that's slightly better.

The rule of thumb is: Always assume you will store everything in one document until you find a reason to break it up. But beware of the trade-offs each way.

Title: Mongodb array vs object


问:
Node.JS or Scala for mobile and web apps
I am coming from a php background with some python as well. I want to start working on a different language for both web and mobile development. I am also interested in real time apps dealing with games.

I am looking at node.js because I can use tools like titanium and/or phone gap to have my apps ported and compiled to native java code, or in a way that makes it runnable on mobile (web views). I like this path because I can use existing JS knowledge to build apps.

I am also looking at scala. I have done some C# as well as tinkered with Java about 5 years ago. And I do like that I can use scala to make native android apps. But unlike node/js which can be made to also work on other mobile os's, this only works on android. In a way, that doesn't really bother me. But scala seems like it would have much better performance for gaming that JS compiled to android. But I do not know how well.

Ine the end I want to focus on socket and REST based web apps for API's that users can have access to, as well as some mobile development. I want to get towards games and interactive apps.

The question is, what features of Scala would benefit me over the node/js side of things for making real time applications on web or mobile? I was looking at using frameworks like lift or play for web.

Node also makes real time easy with socket.io and node handles much of that in the background. This is why I think node could be a great choice. So I was hoping someone could give some insight on features in Node, that would have some benefit over scala. I don't really want to hear 'this is better cause its webscale or related things. I was hoping for more facts about features that would benefit what I want to do. I already understand why node is good. I just dont know much of anything about scala. Or how they may compare for what I want to accomplish.

答:
I am looking at node.js because I can use tools like titanium and/or phone gap to have my apps ported and compiled to native java code, or in a way that makes it runnable on mobile (web views). I like this path because I can use existing JS knowledge to build apps.

Node is a server-side technology. You shouldn't let your app-language decide your server-side language.  Yes, there are some "synergies" to having your front-end and back-end in the same language. But it's no silver bullet, and can cause more headaches than it solves. In fact, the majority of application writers explicitly choose not to do this.

So I was hoping someone could give some insight on features in Node, that would have some benefit over scala.

One reason NOT to use Node is that JavaScript has a lot of warts. (Search for "JavaScript WTF".). If you want JS on the server, prepared to become a JavaScript expert (especially the warts). Also consider CoffeeScript which is helps shave off a few of the warts, but is easily turned into JS. JavaScript is also a scripting language, so tends to be less efficient than Scala.

Scala uses the JVM, and the server-side JVM story is much more mature than Node. But Scala is probably harder to get started in.  I don't know anything about writing apps in Scala, but I'd imagine that's very immature.

Don't think of the question as either-or. You'll be a better developer if you try implementing in both languages. The more languages you know, the better you will program in your favorite language.


问:
Handling timeout in network application
How can I handle timeouts in a network application.

I'm implementing a provisioning system on a Linux server, the code is huge so I'm going to put the algorithm, it works as like this

Read provisioning commands from file

Send it to another server using TCP

Save the request in hash.

Receive the response then

if successful response received then remove request from hash

if failed response received then retry the message

The problem I'm in now is when the program didn't receive the response for a timeout reason then the request will be waiting for a response forever and won't be retried.

And please note that I'll be sending hundreds of commands and I have to monitor the timeout commands for all of them.

I tried to use timer but that didn't help because I'll end up with so many waiting timers and I'm not sure if this is a good way of doing this.

The question is how can I save the message in some data structure and check to remove or retry it later when there is no response from the other end?

Please note that I'm willing to change the algorithm to anything you suggest that could deal with the timeouts.

答:
I'll end up with so many waiting timers and I'm not sure if this is a good way of doing this.

Lots of timers is generally not a problem. Internally, your OS is "doing the right thing" (just setting one timer to the next event, and keeping the rest on a sorted list.)

If you want to reduce the number of timers, round your timeouts to the nearest second (or N seconds) and re-use the timer's you've already set. But this requires a complex data structure.

I'm using hash, sweeping structure here doesn't work

Huh? Your hash should allow you to enumerate the keys. Then you look up each key in the hash, looking for things that haven't been retried in a while. (Informally called "sweeping")  If you only have "hundreds" of events, sweeping the list won't be a performance problem.

(In fact, if we're only talking "hundreds", I'd skip all the timer stuff entirely. Just set up one timer to fire every 5 seconds. Sweep the structure and do any retries needed. It's going to be less code, and not be a performance problem.)

Alternately, keep a sorted list of your events (in addition to the hash). The list can contain just the key to the hash, or pointers to the hash. Then when a timer hits, pop off any events that need to be re-sent. Stop popping when the event isn't due yet, and set another timer for that time-out.

Be sure to worry about how you will gracefully shut-down the service.

Title: Handling timeout in network application


问:
How to optimize calls to multiple APIs at once and return as one set?
I have a web app that searches across 2 APIs right now.  I have my own Restful web service that I call, and it does all the work on the backend to asynchronously call the 2 APIs and concatenate them into one result set for my web app to use.

I want to scale this out and add as many other APIs as I can (currently looking at about 10 more).  But as I add APIs, the call to my service gets (potentially) slower and more complex.  How do I handle one API not responding ... and other issues that arise?

What would be the best way to approach this?  Should I create a service call for each API, that way each one is independent and not coupled to all the other calls?  Is there a way on the backend to handle the multiple API calls without all the extra complexity it adds?

If I go the route of a service call per API, now my client code gets more complex (and I have a lot of clients)?  And it's more work for the client, and since I have mobile apps, it will cost the client more data usage.

If I go one service call, is there a way to set up some sort of connection so I can return data as I get it, in case one service call hangs?

答:
You need to look into threads and/or coroutines (Sometimes called fibers, goroutines, gevents, in different languages).

When a request comes in, you spawn off 10 threads/coroutines, then wait for them all to respond, or for a timeout. To the "web server", your request is simply sleeping for a few seconds. But other threads/coroutines are actively doing work.  If the work isn't done in N seconds, the threads/coroutines are killed off and only the results you have are returned.

Example in Go.

Threads are heavy weight (harder to scale), but generally better supported depending on the language. Coroutines are more efficient (less RAM, less CPU), but have problems on some languages/libraries.


问:
Unit testing - Database coupled app
What would be the best approach at unit testing a model that integrates into an application that is tightly coupled to database?

The specific scenario here is a shopping cart - I'd like to be able to test the adding removing and retrieving of items from the cart as well as pricing logic etc. This in my mind all requires database access though I have read several times that database access should be avoided.

答:
This is fairly easy to do with junit if a little long winded.

The "setup" should define and populate a set of temporary tables.

You can then perform the unit tests for all the update, insert, delete functionality.

For each test you call your update method then run some SQL to verify the expected result.

In the "teardown" phase you drop all the tables.

In this way you always run the same tests on the same initial data. If you keep the tables between tests they end up being "polluted" by failed tests, also, a consistent "insert" test is almost impossible as you need to keep inventing new keys on every test.

Title: Unit testing - Database coupled app


问:
How is a "Software Developer" different from a "Software Consultant"? What makes a consultant?
I have seen a lot of people claiming themselves to be a "software consultant". These consultants do what a normal software developer does, write code, estimate tasks, fix bugs and attend meetings etc. The only difference being the financials, consultants end up earning more. Then how is a software developer different from a "consultant"?

In addition to the main question, I would like to know how can a software developer become a consultant? Are there any specific guidelines for a consultant? Do they need to amass certifications and write up research papers? Please do not confuse the software consultant with a management consultant. Software consultants I have seen are not managers.

答: I think you guys have the wrong idea.  Differentiate between software consultants who have their own company and individually consult vs software consultants who work for the Big 4.  Consultants have more business skills/relationship management focus and limited expertise developing.  Software developers are mostly hands on, hardcore technical and over a period of time their hard skill set becomes stronger than a software consultant's.  A consultant has to split his/her attn between business and technical work, so his/her skills trend more towards business as seniority rises.  If it is a software consultant that is individually operating, then that is someone who is proven to be awesome and can afford to give advice and services at a high price.  The software consultants who work at places like the Big 4 consulting firms are more like jacks of all trades.  A company like Google or Amazon or Apple would rarely touch these types of people after consulting is done with them unless they kept their hard technical skills up outside of work.</p>


问:
Pointer access and cache coherency
To my understanding, when you access a variable, that variable and the surrounding area of memory is put into the L1 cache. If I'm wrong here, please tell me.

Now my question is, say I have an array of pointers, and I want to iterate through them all performing operation X. If I first have to access the pointer, to get the address of the actual data, does this mean that the memory near the pointer will be put into cache, then the memory near the data, then back to the pointer, then to the data etc? i.e. Cache thrashing?

If this is the case, how might one go about keep cache coherency?

答:
Whether or not the data will evict the pointer from cache depends on how how much memory you actually touch, how memory addresses are mapped to cache lines, and on the replacement policy. The most common replacement policy is Least Recently Used (sometimes just approximating the least used) where the new data will replace the data which was used the least recently in the cache. Memory addresses are commonly mapped in N-way sets where multiple memory addresses map to the same cache line, and each address can map to N cache lines (see here). N will probably be 2 or 4.

Under these conditions, you will almost assuredly not have cache thrashing if you are dereferencing a pointer then using the data IF the data you touch after dereferencing fits into the cache line. In both memory accesses, the least recently used cache line is definitely not the line with the pointer (in case of the data access), or the data (in case of the pointer dereferencing) since those were the last (most recently) touched cache lines. If you touch more memory than what is in the cache line with the data after dereferencing the pointer then it is possible that you will evict the pointer data from cache, but that depends on where the data is in memory, and how much you touch. It is possible that more data access will not evict the pointers if the addresses do not map to the cache line with the pointers or the pointer line is not the least recently used in the set of lines the addresses map to, but since the memory address of your data allocation is usually not known until the program runs it is hard to say either way just from source code.

It is probably possible to have your data and pointers allocated at specific memory addresses just to keep hitting cache as much as possible, but that would require you know the policies of the cache of the processor running your code, and that the compiler doesn't make optimizations which change the data access patterns without you knowing. It would also be processor specific, with different cache policies on different processors making any micro optimization on this scale worthless. As I note below, it is very difficult to find information about specific policies on common processors so it is probably not worth thinking about this kind of optimization at all. In general, consecutive memory address accesses are the best way of hitting cache if you are only touching things once (like in your loop over the pointers). No other optimization is needed.

This is all assuming a single processor with a single thread. Multiple threads and multiple processors throw wrenches in reasoning about cache. Multiple threads on a single processor means that another thread could start running in the middle of your loop and when your thread starts running again, the cache is in a completely different state and the whole process starts over, but otherwise not much is different.

If you have a multi threaded loop (think one thread per pointer) running on multiple processors, then the whole cache thing is pretty difficult to reason about. The order of execution could be rearranged, or consecutive pointers could be dereferenced on different processors. Both situations means that the cache probably has not be primed by previous pointer dereferences or data accesses. In this case you should consider chunking data so a thread accesses a range of pointers instead of a single one so the cache can actually be used.

Remember that the memory you touch after dereferencing has to be SMALL. A few (read 2 or 4) ints would fit in a cache line, but an object with many members might not. If you access data stored more than a cache line's size from the beginning of the object, you are evicting more from cache and thus have more chance of evicting the pointers.

Finding data about the caches in Intel and AMD processors is kind of difficult, but I found this link from 2010 saying that Intel uses a pseudo LRU policy on a 4-way associative cache for L2 cache, and the same policy for L1 cache (no set associativity is mentioned) on at least one of their processor architectures. It should be noted that the replacement policy is an integral component in making cache speed up programs. I would not be surprised in the least if they are more complicated or harder to reason about than what I presented above since unmodified LRU is not universally the best replacement policy. Actual replacement policies probably have much more complicated rules in the name of keeping cache hits high, but exact details would be scarce since they are a competitive edge in the performance benchmark wars.

Title: Pointer access and cache coherency


问:
What do goroutines, Ruby Fibers, etc. look like to the OS/Kernel?
In process concurrency and thread concurrency it's quite obvious how the kernel sees these as they map directly to real things that the kernel manages. When it comes to Golang goroutines and Ruby Fibers (these are similar things right?) I'm clueless as to how these are managed. Are they managed by the respective languages implementation/Virtual Machine(I know Go doesn't have a VM) or are they mapped to something that the kernel is better at handling?</p>

答:
That depends on the implementation. YARV implements Fibers itself, JRuby implements them as Java Threads, except on JVMs which have the proprietary experimental Coroutine extension (which is not part of the JVM Specification) where it implements them as JVM Coroutines.

It's the same as Threads, really. MRI implements Threads itself, YARV implements them as POSIX/Windows Threads, JRuby implements them as JVM Threads, IronRuby implements them as CLI Threads. Rubinius originally implemented them itself and later switched to implementing them as POSIX/Windows Threads.

The BEAM Erlang VM implements Processes itself. The Erjang Erlang VM implements them as Kilim Actors.

In other words: what Ruby Fibers etc. look like to the Kernel depends on what the author of the particular implementation wants them to look like to the Kernel.