答:
Sounds like Dan derrived his example from this article: The Paperboy, The Wallet,
and The Law Of Demeter

Law Of Demeter A method of an object should invoke only the methods of the following kinds of objects:

itself

its parameters

any objects it creates/instantiates

its direct component objects

When and How to Apply The Law Of Demeter

So now you have a good understanding of the law and it's benefits, but
  we haven't yet discussed how to identify places in existing code where
  we can apply it (and just as important, where NOT to apply it...)

Chained 'get' Statements - The first, most obvious place to apply the Law Of Demeter is places of code that have repeated get()
  statements,

value = object.getX().getY().getTheValue();

as if when our canonical person for this example were pulled over by
  the cop, we might see:

license = person.getWallet().getDriversLicense();

lots of 'temporary' objects - The above license example would be no better if the code looked like,

Wallet tempWallet = person.getWallet();
  license = tempWallet.getDriversLicense();

it is equivalent, but harder to detect.

Importing Many Classes - On the Java project I work on, we have a rule that we only import classes we actually use; you never see
  something like

import java.awt.*;

in our source code. With this rule in place, it is not uncommon to
  see a dozen or so import statements all coming from the same package.
  If this is happening in your code, it could be a good place to look
  for obscured examples of violations. If you need to import it, you are
  coupled to it. If it changes, you may have to as well. By explicitly
  importing the classes, you will begin to see how coupled your classes
  really are.

I understand that your example is in Ruby, but this should apply across all OOP languages.

Title: Rails: Law of Demeter Confusion

OwnerDisplayName: Mr. Polywhirl


问:
Finding the lowest average Hamming distance when the order of the strings matter
I have a sequence of binary strings that I want to find a match for among a set of longer sequences of binary strings. A match means that the compared sequence gives the lowest average Hamming distance when all elements in the shorter sequence have been matched against a sequence in one of the longer sets.

Let me try to explain with an example. I have a set of video frames that have been hashed using a perceptual hashing algorithm so that the video frames that look the same has roughly the same hash. I want to match a short video clip against a set of longer videos, to see if the clip is contained in one of these. This means that I need to find out where the sequence of the hashed frames in the short video has the lowest average Hamming distance when compared with the long videos.

The short video is the sub strings Sub1, Sub2 and Sub3, and I want to match them against the hashes of the long videos in Src. The clue here is that the strings need to match in the specific order that they are given in, e.g. that Sub1 always has to match the element before Sub2, and Sub2 always has to match the element before Sub3. In this example it would map thusly: Sub1-Src3, Sub2-Src4 and Sub3-Src5.

So the question is this: is there an algorithm for finding the lowest average Hamming distance when the order of the elements compared matter? The naïve approach to compare the substring sequence to every source string won't cut it of course, so I need something that preferably can match a (much) shorter sub string to a set of million of elements. I have looked at MVP-trees, BK-trees and similar, but everything seems to only take into account one binary string and not a sequence of them.

```<code>Sub1: 100111011111011101
Sub2: 110111000010010100
Sub3: 111111010110101101

Src1: 001011010001010110
Src2: 010111101000111001
Src3: 101111001110011101
Src4: 010111100011010101
Src5: 001111010110111101
Src6: 101011111111010101
</code>```

I have added a calculation of the examples below. (The Hamming distances aren't correct, but it doesn't matter)

```<code>**Run 1.**
dist(Sub1, Src1) = 8
dist(Sub2, Src2) = 10
dist(Sub3, Src3) = 12
average = 10

**Run 2.**
dist(Sub1, Src2) = 10
dist(Sub2, Src3) = 12
dist(Sub3, Src4) = 10
average = 11

**Run 3.**
dist(Sub1, Src3) = 7
dist(Sub2, Src4) = 6
dist(Sub3, Src5) = 10
average = 8

**Run 4.**
dist(Sub1, Src3) = 10
dist(Sub2, Src4) = 4
dist(Sub3, Src5) = 2
average = 5
</code>```

So the winner here is sequence 4 with an average distance of 5.

答: Maybe you could just concatenate your srcs and subs respectively. After that you can use a sequence allignment algorithm of your taste, like the Smith-Waterman algorithm or the more general Needleman-Wunsch algorithm.</p>

ContentLicense: CC BY-SA 3.0


问:
Writing the minimum code to pass a unit test - without cheating!
When doing TDD and writing a unit test, how does one resist the urge to "cheat" when writing the first iteration of "implementation" code that you're testing?

For example:

Let's I need to calculate the Factorial of a number.  I start with a unit test (using MSTest) something like:

```<code>[TestClass]
public class CalculateFactorialTests
{
    [TestMethod]
    public void CalculateFactorial_5_input_returns_120()
    {
        // Arrange
        var myMath = new MyMath();
        // Act
        long output = myMath.CalculateFactorial(5);
        // Assert
        Assert.AreEqual(120, output);
    }
}
</code>```

I run this code, and it fails since the CalculateFactorial method doesn't even exist.  So, I now write the first iteration of the code to implement the method under test, writing the minimum code required to pass the test.

The thing is, I'm continually tempted to write the following:

```<code>public class MyMath
{
    public long CalculateFactorial(long input)
    {
        return 120;
    }
}
</code>```

This is, technically, correct in that it really is the minimum code required to make that specific test pass (go green), although it's clearly a "cheat" since it really doesn't even attempt to perform the function of calculating a factorial.  Of course, now the refactoring part becomes an exercise in "writing the correct functionality" rather than a true refactoring of the implementation.  Obviously, adding additional tests with different parameters will fail and force a refactoring, but you have to start with that one test.

So, my question is, how do you get that balance between "writing the minimum code to pass the test" whilst still keeping it functional and in the spirit of what you're actually trying to achieve?

答:
Clearly an understanding of the ultimate goal, and the achievement of an algorithm that meets that goal, is required.

TDD is not a magic bullet for design; you still have to know how to solve problems using code, and you still have to know how to do that at a level higher than a few lines of code to make a test pass.

I like the idea of TDD because it encourages good design; it makes you think about how you can write your code so that it is testable, and generally that philosophy will push the code towards a better design overall. But you still have to know how to architect a solution.

I do not favor reductionist TDD philosophies that claim you can grow an application by simply writing the smallest amount of code to pass a test.  Without thinking about architecture, this won't work, and your example proves that.

Uncle Bob Martin says this:

If you're not doing Test Driven
Development, it's very difficult to
call yourself a professional. Jim
Coplin called me on the carpet for
this one. He didn't like that I said
that. In fact, his position right now
is that Test Driven Development is
destroying architectures because
people are writing tests to the
abandon of any other kind of thought
and tearing their architectures apart
in the mad rush to get tests to pass
and he's got an interesting point,
that's an interesting way to abuse the
ritual and lose the intent behind the
discipline.

if you're not thinking through the
architecture, if what you're doing
instead is ignoring architecture and
throwing tests together and getting
them to pass, you're destroying the
thing that will allow the building to
stay up because it's the concentration
on the structure of the system and
solid design decisions that help the
system maintain its structural
integrity.

You cannot simply just throw a whole
bunch of tests together and make them
pass for decade after decade after
decade and assume that you're system
is going to survive. We don't want to
evolve ourselves into hell. So a good
test driven developer is always
conscious of making architectural
decisions, always thinking of the big
picture.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
Code Review tools - to use or not?
On my dev team, we're doing code reviews, however not in a proper way i believe.

The issues our process suffers from:

Not enough time is allocated for proper code review.

Doing reviews is not mandatory - many times it is simply not done.

Devs sit together for reviews, due to lack of another easy mechanism for doing it "offline" without spending both developers' time.

My question is: can integration of a tool for code reviews improve  the points mentioned above? Is it not needed?

I would love to hear from positive/negative experiences.

答: By actually enforcing code reviews with tools like gerrit or Crucible you can solve part 2 and 3 of your problem. Part 1 is more a process / social problem you'll never fix with software.</p>

Title: Code Review tools - to use or not?


答:
No you're not doing code reviews properly (obviously!). So the question remains whether there's something wrong with your code that it needs review sessions? (ie if you're shipping working code, code reviews are a solution looking for a problem).

If you think they would be beneficial, then I'd start work with a code review tool you can use in a 'as and when' mode - so you upload a code review request but it doesn't stop the rest of the process of committing and building code from happening. I think if you added the review to the workflow process that prevented commits until after review, you'd just end up frustrated and sidestepping the reviews. Be honest with yourselves in this case.

But if you could review code when you have time, then it becomes a good way of showing what you did to solve a work task, and you can always retroactively fix code review defects by raising a subsequent bug.

Good code review tools are ReviewBoard - a python base website. You upload diffs to the site and can then assign and comment on them. VMWare developed it for their own purposes.
Gerrit works well if you use git.
Redmine has a nice code review plugin that allows reviews based on any commit, you just create a new review as just another tracker ticket. Its pleasant to use and doesn;'t get in your way.

Title: Code Review tools - to use or not?

Body:
On my dev team, we're doing code reviews, however not in a proper way i believe.

The issues our process suffers from:

Not enough time is allocated for proper code review.

Doing reviews is not mandatory - many times it is simply not done.

Devs sit together for reviews, due to lack of another easy mechanism for doing it "offline" without spending both developers' time.

My question is: can integration of a tool for code reviews improve  the points mentioned above? Is it not needed?

I would love to hear from positive/negative experiences.


问:
Class or Dictionary
I want to create a immutable Scale class in C#.

```<code>public sealed class Scale
{
    string _Name;
    string _Description;
    SomeOrderedCollection _ScaleValueDefinitions;
    Unit _Unit

    // properties
    ....
    // methods
    ContainsValue(double value)
    ....

    // constructors
    // all parameters except scalevaluedefinitions are optional
    // for a Scale to be useful atleast 1 ScaleValueDefinition should exist
    public Scale(string name, string description, SomeOrderedCollection scaleValueDefinitions, unit)
    { /* initialize */}
}
</code>```

so first a ScaleValueDefinition should be represented by to values:

Value (double)

Definition (string)

these values are known before the Scale class is created and should be unique.
so what is the best approach.

create a immutable class ScaleValueDefinition with value and definition as properties and use it in a list.

use a dictionary.

use another way i didn't think of...

and how to implement it.
for option 1. i can use params ScaleValueDefinition[] ValueDefinitions in the constructor, but how to do it for the other options?

and as last at what amount of value's (properties) should i choose one option over the other?

答: It's rather opinion based but explicit classes seem to be better as they really express your intent. Also, code is easier to maintain - imagine changing keys of your dictionary all over the code, whereas for a class one place refactoring would suffice.</p>

Title: Class or Dictionary

OwnerDisplayName: BartoszKP


答:
like this maybe?</p>

```<code>public sealed class Scale<TUnit> : IReadOnlyList<TUnit>
{
    private readonly string name;
    private readonly string description;
    private readonly IList<TUnit> definition;

    public Scale(
             string name,
             string description,
             IEnumerable<TUnit> definition) : this(name, description)
    {
        this.definition = definition.ToList();
    }

    public Scale(
             string name,
             string description,
             params TUnit[] definition) : this(name, description)
    {
        this.definition = definition;
    }

    private Scale(
             string name,
             string description)
    {
        this.name = name;
        this.description = description;
    }

    public string Name
    {
        get { return this.name; }
    }

    public string Description
    {
        get { return this.description; }
    }

    public TUnit this[int index]
    {
        get { return this.definition[index]; }
    }

    public int Count
    {
        get { return this.definition.Count; )
    }

    public IEnumerator<TUnit> GetEnumerator()
    {
        return this.definition.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}
</code>```

Title: Class or Dictionary

Body:
I want to create a immutable Scale class in C#.

```<code>public sealed class Scale
{
    string _Name;
    string _Description;
    SomeOrderedCollection _ScaleValueDefinitions;
    Unit _Unit

    // properties
    ....
    // methods
    ContainsValue(double value)
    ....

    // constructors
    // all parameters except scalevaluedefinitions are optional
    // for a Scale to be useful atleast 1 ScaleValueDefinition should exist
    public Scale(string name, string description, SomeOrderedCollection scaleValueDefinitions, unit)
    { /* initialize */}
}
</code>```

so first a ScaleValueDefinition should be represented by to values:

Value (double)

Definition (string)

these values are known before the Scale class is created and should be unique.
so what is the best approach.

create a immutable class ScaleValueDefinition with value and definition as properties and use it in a list.

use a dictionary.

use another way i didn't think of...

and how to implement it.
for option 1. i can use params ScaleValueDefinition[] ValueDefinitions in the constructor, but how to do it for the other options?

and as last at what amount of value's (properties) should i choose one option over the other?

Body:
like this maybe?

public sealed class Scale<TUnit> : IReadOnlyList<TUnit>
{
    private readonly string name;
    private readonly string description;
    private readonly IList<TUnit> definition;

    public Scale(
             string name,
             string description,
             IEnumerable<TUnit> definition) : this(name, description)
    {
        this.definition = definition.ToList();
    }

    public Scale(
             string name,
             string description,
             params TUnit[] definition) : this(name, description)
    {
        this.definition = definition;
    }

    private Scale(
             string name,
             string description)
    {
        this.name = name;
        this.description = description;
    }

    public string Name
    {
        get { return this.name; }
    }

    public string Description
    {
        get { return this.description; }
    }

    public TUnit this[int index]
    {
        get { return this.definition[index]; }
    }

    public int Count
    {
        get { return this.definition.Count; )
    }

    public IEnumerator<TUnit> GetEnumerator()
    {
        return this.definition.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

OwnerDisplayName: Jodrell


答:
You haven't mentioned whether you will need to look up definitions by their value, which of course is the main purpose of a dictionary. Otherwise, I don't see any reason to use a dictionary.

If you need to do lookups, I would actually use both: that is, a Dictionary<double, ScaleValueDefinition>. That way, I can look up the definitions by the value, but also retain a reference to the value I looked up. This also means the dictionary can be dynamically generated from a sequence of ScaleValueDefinitions (using ToDictionary), and the order of that sequence can be stored, without forcing the user to pass in an OrderedDictionary:

```<code>private IEnumerable<ScaleValueDefinition> _internalOrderedCollection;
private Dictionary<double, ScaleValueDefinition> _internalDictionary;

public Scale(string name, string description, IEnumerable<ScaleValueDefinition> scaleValueDefinitions) {
    _name = name;
    _description = description;
    _internalOrderedCollection = scaleValueDefinitions.ToList();
    _internalDictionary = scaleValueDefinitions.ToDictionary(svd => svd.Value);
}
</code>```

For immutability, you can simply wrap the internal dictionary in a public ReadOnlyDictionary.

Title: Class or Dictionary

Body:
You haven't mentioned whether you will need to look up definitions by their value, which of course is the main purpose of a dictionary. Otherwise, I don't see any reason to use a dictionary.

If you need to do lookups, I would actually use both: that is, a Dictionary<double, ScaleValueDefinition>. That way, I can look up the definitions by the value, but also retain a reference to the value I looked up. This also means the dictionary can be dynamically generated from a sequence of ScaleValueDefinitions (using ToDictionary), and the order of that sequence can be stored, without forcing the user to pass in an OrderedDictionary:

private IEnumerable<ScaleValueDefinition> _internalOrderedCollection;
private Dictionary<double, ScaleValueDefinition> _internalDictionary;

public Scale(string name, string description, IEnumerable<ScaleValueDefinition> scaleValueDefinitions) {
    _name = name;
    _description = description;
    _internalOrderedCollection = scaleValueDefinitions.ToList();
    _internalDictionary = scaleValueDefinitions.ToDictionary(svd => svd.Value);
}

For immutability, you can simply wrap the internal dictionary in a public ReadOnlyDictionary.

OwnerDisplayName: nmclean


问:
What's the difference between the code inside a finally clause and the code located after catch clause?
My java code is just like below:

```<code>public void check()throws  MissingParamException{
    ......
}
public static void main(){
    PrintWriter out = response.getWriter();
    try {
        check();
    } catch (MissingParamException e) {
        // TODO Auto-generated catch block
        out.println("message:"+e.getMessage());
        e.printStackTrace();
        out.close();
    }finally{
        out.close();
    }
    //out.close();
}
</code>```

Then, my confusion is: what the difference if I put out.close() in a finally code block or if I just remove finally code block and put out.close() behind catch clause (which has been commented in the code). I know that in both ways, the out.close() will be executed because I know that whether the exception happened, the code behind the catch clause will always be executed.

答:
The difference is that if your check() function throws any exception OTHER than MissingParamException, anything below try/catch will not get executed because your function's stack will get unrolled until a catch is found that will handle that exception of that type (or possibly thread exits if exception is not handled).  However, the code you put inside the finally clause is guaranteed to be executed no matter what happens inside the try block.

So in your case leaving out.close() inside the finally block would be a more correct thing to do.


答:
Let's do the case analysis.

No exception thrown:
 No difference

MissingParamException thrown:
 No difference

Some exception you don't have a catch for i. e. Null Ref:
 If it is in the finally out.close() will be called.  If it is after everything then it will not be called.

Incidentally you call close in the catch block and the finally block that means when a MissingParamException is thrown you call close twice.  Not a big deal, just not necessary.

Title: What's the difference between the code inside a finally clause and the code located after catch clause?

Body:
My java code is just like below:

```<code>public void check()throws  MissingParamException{
    ......
}
public static void main(){
    PrintWriter out = response.getWriter();
    try {
        check();
    } catch (MissingParamException e) {
        // TODO Auto-generated catch block
        out.println("message:"+e.getMessage());
        e.printStackTrace();
        out.close();
    }finally{
        out.close();
    }
    //out.close();
}
</code>```

Then, my confusion is: what the difference if I put out.close() in a finally code block or if I just remove finally code block and put out.close() behind catch clause (which has been commented in the code). I know that in both ways, the out.close() will be executed because I know that whether the exception happened, the code behind the catch clause will always be executed.


答:
The finally {} block is always called (unless you call exit() before finally is reached - but you won't be doing that most of the time).

The purpose of finally is to clean up any resources allocated in the try {} block, even if something was thrown and it hit the catch{} block.

Consider the code:

```<code>public class Hello {

    public static void main(String[] args) {
        hello();
    }

    public static void hello() {
        try {
            System.out.println("hi");
            return;
        } catch (RuntimeException e) {
        } finally {
            System.out.println("finally");
        }
    }
}
</code>```

While there isn't any resource allocation in this, just pretend there is.  This will print out:

```
hi
finally
```

If you had opened a file in the try block, the finally is the place to clean it up.  If you had opened one file, and then tried to open another one (that threw an exception), the finally is the place to clean that up.

If there was an uncaught exception by the catch block, then the finally would run, and the exception would get passed on up.

Putting out.close() in the catch and the finally is redundant - because it will be run in the finally block - on a caught exception or successful completion of the try.

With the existing code, the following code paths are possible:

No exception:

check() - no exception thrown

finally { } - out.close

Caught exception:

check() - MissingParamException thrown

catch { } - stuff and out.close

finally { } - out.close

Uncaught exception:

check() - NPE thrown

finally { } - out.close

You should be able to see from this, the finally is always called, and in the caught exception, out.close() is invoked twice.

The associated spec is §14.20.2 in Java SE 7 language specification.

Body:
The finally {} block is always called (unless you call exit() before finally is reached - but you won't be doing that most of the time).

The purpose of finally is to clean up any resources allocated in the try {} block, even if something was thrown and it hit the catch{} block.

Consider the code:

public class Hello {

    public static void main(String[] args) {
        hello();
    }

    public static void hello() {
        try {
            System.out.println("hi");
            return;
        } catch (RuntimeException e) {
        } finally {
            System.out.println("finally");
        }
    }
}

While there isn't any resource allocation in this, just pretend there is.  This will print out:

hi
finally

If you had opened a file in the try block, the finally is the place to clean it up.  If you had opened one file, and then tried to open another one (that threw an exception), the finally is the place to clean that up.

If there was an uncaught exception by the catch block, then the finally would run, and the exception would get passed on up.

Putting out.close() in the catch and the finally is redundant - because it will be run in the finally block - on a caught exception or successful completion of the try.

With the existing code, the following code paths are possible:

No exception:

check() - no exception thrown

finally { } - out.close

Caught exception:

check() - MissingParamException thrown

catch { } - stuff and out.close

finally { } - out.close

Uncaught exception:

check() - NPE thrown

finally { } - out.close

You should be able to see from this, the finally is always called, and in the caught exception, out.close() is invoked twice.

The associated spec is §14.20.2 in Java SE 7 language specification.


问:
Why do large IT projects tend to fail or have big cost/schedule overruns?
I always read about large scale transformation or integration project that are total or almost total disaster. Even if they somehow manage to succeed  the cost and schedule blow out is enormous. What is the real reason behind large projects being more prone to failure. Can agile be used in these sort of projects or traditional approach is still the best.

One example from Australia is the Queensland Payroll project where they changed test success criteria to deliver the project.

See some more failed projects in this SO question (on Wayback Machine)

Have you got any personal experience to share?

答:
Michael Krigsman over on ZDNet has a blog devoted to "IT Project Failures," that may be of interest here.

Another point is that with long projects that span years, there will generally either be upgrades to consider or alternative solutions,e.g. could a project now be done in the cloud versus on-site for something starting to come up more and more, that in considering these this wasn't a given when the project was started.  For example, while one could start while something is at 6.0, by the time the first phase is done there may well be a 6.3 or 6.4 out and the question of when to upgrade is being asked.  Changes in scope and desired functionality, either because requirements weren't gathered correctly or someone changed their mind, are another couple of points that have already been covered quite a bit.


答:
Most has been answered in the other answers but one thing not:
If you choose to not use finally and your code goes into you catch block and there's another exception in your catch block then no close will be called at all.</p>


问:
Building a database class in PHP
I wonder if I should write a database class for my application, and if so, how to accomplish it?

Over there on SO, a guy mentioned it should be written as an abstract class. However, I can't understand why this would be a benefit.

Do I understand correctly, that if I would write an abstract class, every other class that methods will need a database connection, could simply extend this abstract class and have its own database object? If so, how is this different from a "normal" class where I could instantiate an database object?

Another method would be to completely forget about my own class and to instantiate a mysqli object on demand.

What do you recommend?

答:
Yes, you should use classes to access your database.
A good link for further reading on that is to look up the Active Record Design Pattern and Object Relational Mapping

The benefit of this can be seen in the DRY Principle and the Law of Demeter question which was asked previously. By creating an abstract data access class, you keep the data access layer part of your application from leaking into your model/database entity classes AND you don't have to repeat yourself each time you have to make a new database model/entity.

Ok, so back to your question, so now, we build an abstract class to handle the CRUD for our database entities, so now, we only need to extend that abstract class and probably set some variables each time we add a new entity in the database. It makes the pain of writing SQL for your tables less annoying and much easier to handle by moving them all out to the abstract class as well as makes the data access layer of your application much manageable especially if you have a bazzillion models/database entities.

So whats the difference between making your abstract class and making a database model class then instantiating it with a database connection? Or the going straight to just using mysqli?

With the abstract class, you only need to code the data access layer of your application ONCE

Your code becomes DRY by eliminating the redundant database initializations

Better maintainability, you only need to change one part of your code to change how you access the database!

SQL Haters delight! They no longer need to directly touch SQL statements when dealing with ORMs

But as we are programmers, I would suggest not to rebuild this from scratch. No need to reinvent the wheel as they would say. There are already frameworks out there for PHP that handle ORM elegantly. You can look up popular MVC frameworks for PHP like Yii and Kohana.

Title: Building a database class in PHP


问:
Should I close database connections after use in PHP?
I wonder if I should close any unnecessary database connection inside of my PHP scripts.

I am aware of the fact that database connections are closed implicitly when the block stops executing and 'manually' closing the connections could kinda bloat the codebase with unnecessary code.

But shouldn't I do so in order to make by code as readable and as easy understandable as possible, while also preventing several possible issues during run time?

Also, if I would do, would it be enough to unset() my database object?

答:
Yes, it of-course helps. Assume you are building an application, where clients do normal operations with your tables. Now, if the application is heavy and processing intrinsic, it is likely that your application will slow down with vast number of open connections, which will remain idle for a very long duration.
If you explicitly ensure that connection is open for the duration a client is performing some action, you may improve on processing power. Besides, its better to clean up mess quickly than to wait for help !</p>


答:
Just write more tests.  Eventually, it would be shorter to write

```<code>public long CalculateFactorial(long input)
{
    return input <= 1 ? 1 : CalculateFactorial(input-1)*input;
}
</code>```

than

```<code>public long CalculateFactorial(long input)
{
    switch (input) {
       case 0: return 1;
       case 1: return 1;
       case 2: return 2;
       case 3: return 6;
       case 4: return 24;
       case 5: return 120;
    }
}
</code>```

:-)

Title: Writing the minimum code to pass a unit test - without cheating!

Body:
When doing TDD and writing a unit test, how does one resist the urge to "cheat" when writing the first iteration of "implementation" code that you're testing?

For example:

Let's I need to calculate the Factorial of a number.  I start with a unit test (using MSTest) something like:

```<code>[TestClass]
public class CalculateFactorialTests
{
    [TestMethod]
    public void CalculateFactorial_5_input_returns_120()
    {
        // Arrange
        var myMath = new MyMath();
        // Act
        long output = myMath.CalculateFactorial(5);
        // Assert
        Assert.AreEqual(120, output);
    }
}
</code>```

I run this code, and it fails since the CalculateFactorial method doesn't even exist.  So, I now write the first iteration of the code to implement the method under test, writing the minimum code required to pass the test.

The thing is, I'm continually tempted to write the following:

```<code>public class MyMath
{
    public long CalculateFactorial(long input)
    {
        return 120;
    }
}
</code>```

This is, technically, correct in that it really is the minimum code required to make that specific test pass (go green), although it's clearly a "cheat" since it really doesn't even attempt to perform the function of calculating a factorial.  Of course, now the refactoring part becomes an exercise in "writing the correct functionality" rather than a true refactoring of the implementation.  Obviously, adding additional tests with different parameters will fail and force a refactoring, but you have to start with that one test.

So, my question is, how do you get that balance between "writing the minimum code to pass the test" whilst still keeping it functional and in the spirit of what you're actually trying to achieve?

Body:
Just write more tests.  Eventually, it would be shorter to write

public long CalculateFactorial(long input)
{
    return input <= 1 ? 1 : CalculateFactorial(input-1)*input;
}

than

public long CalculateFactorial(long input)
{
    switch (input) {
       case 0: return 1;
       case 1: return 1;
       case 2: return 2;
       case 3: return 6;
       case 4: return 24;
       case 5: return 120;
    }
}

:-)


问:
TotalPhase Aardvark driver's GPL license
I'm using an SPI host adapter for a project. The Aardvark from TotalPhase. And I did something crazy, I read that EULA license that everyone just clicks through.

The driver installation license includes these bits:

This driver installer package also includes a WIN32 driver that is
entirely based on the libusb-win32 project (release 0.1.10.1).

...

LICENSE:

The software in this package is distributed under the following
licenses:

Driver:   GNU General Public License (GPL)
 Library, Test
Files:    GNU Lesser General Public License (LGPL)

Now, my understanding of of the GPL is that it's sticky and viral. If you include software then the whole project has to be released under the GPL (if you distribute it, you can do whatever you want with in-house projects).

If the driver was like the library, and was licensed under the LGPL, it could be used by my closed source proprietary project, as long as it's source and license was passed along with it. But it's not, it's pure GPL.

If I include this driver in my project and distribute it, am I required to release my project under the GPL?

答:
The only difference between GPL and LGPL is that GPL stops at process boundary while LGPL stops at dynamic link boundary.

Since the driver runs in different process than your proprietary code, the license does not spread to your code. Distributing together does not matter; running in the same process does.

Remember, that since the library is LGPL you must link it dynamically. If you link it statically, it's license would apply to your code.


问:
Is avoiding the private access specifier in PHP justified?
I come from a Java background and I have been working with PHP for almost a year now. I have worked with WordPress, Zend and currently I'm using CakePHP. I was going through Cake's lib and I couldn't help notice that Cake goes a long way avoiding the "private" access specifier. Cake says

Try to avoid private methods or variables, though, in favor of protected
     ones. The latter can be accessed or modified by subclasses, whereas private
     ones prevent extension or re-use.

in this tutorial.

Why does Cake overly shun the "private" access specifier while good OO design encourages its use i.e to apply the most restrictive visibility for a class member that is not intended to be part of its exported API? I'm willing to believe that "private" functions are difficult test, but is rest of the convention justified outside Cake? or perhaps it's just a Cake convention of OO design geared towards extensibility at the expense of being a stickler for stringent (or traditional?) OO design?

答:
The PHP world is full of bad advice, and your quote is yet another example of it. CakePHP is an entry level framework, and its documentation is written with less experienced developers in mind. That, however, doesn't justify so naive a statement, especially in the framework's official documentation.

Whether you'll use private or protected is a design choice. If there's no reason for your properties and functions to be inherited, use private. If, on the other hand, your design calls for those properties and functions to be available to subclasses, use protected.

It really is as simple as that.


问:
Architecting multi-model multi-DB ASP.NET MVC solution
I have an ASP.NET MVC 4 solution that I'm putting together, leveraging IoC and the repository pattern using Entity Framework 5. I have a new requirement to be able to pull data from a second database (from another internal application) which I don't have control over.

There is no API available unfortunately for the second application and the general pattern at my place of work is to go direct to the database.

I want to maintain a consistent approach to modeling the domain and use entity framework to pull the data out, so thus far I have used Entity Framework's database first approach to generate a domain model and database context over the top of this.

However, I've become a little stuck on how to include the second domain model in the application.

I have a generic repository which I've now moved out to a common DataAccess project, but short of creating two distinct wrappers for the generic repository (so each can identify with a specific database context), I'm struggling to see how I can elegantly include multiple models?

答:
Taking a step back from your actual question, you could be in for a whole world of pain if the rug is pulled from under you by the other project changing it's schema.

You acknowledge the other system does not have an API for you to use. I would push for this to be created.

The other project may not be be in an active workstream, have budget etc, so maybe your project will have to pay for it in some fashion, and maybe even you have to do the work.


答:
I believe this link answers your question to some extent.
It has used OOP approach and nicely explained. Here is a simple skeleton from the link:`</p>

```<code>class Database
{
    public function connect()   {   }
    public function disconnect()    {   }
    public function select()        {   }
    public function insert()        {   }
    public function delete()        {   }
    public function update()    {   }
}  `
</code>```

Title: Building a database class in PHP

Body:
I wonder if I should write a database class for my application, and if so, how to accomplish it?

Over there on SO, a guy mentioned it should be written as an abstract class. However, I can't understand why this would be a benefit.

Do I understand correctly, that if I would write an abstract class, every other class that methods will need a database connection, could simply extend this abstract class and have its own database object? If so, how is this different from a "normal" class where I could instantiate an database object?

Another method would be to completely forget about my own class and to instantiate a mysqli object on demand.

What do you recommend?

Body:
I believe this link answers your question to some extent.
It has used OOP approach and nicely explained. Here is a simple skeleton from the link:`

class Database
{
    public function connect()   {   }
    public function disconnect()    {   }
    public function select()        {   }
    public function insert()        {   }
    public function delete()        {   }
    public function update()    {   }
}  `


问:
Ping one remote server from another remote server
It's simple to ping a server in C#, but suppose I have servers A, B and C.

A connects to B.

A asks B to ping C, to check that B can talk to C.

A needs to read the outcome.

Now, first of all is this possible without installing an application onto B? In other words, can I perform the entire check from just running a program on A?

If so, can anyone suggest the route I would take to achieve this? I've looked at sockets but from the examples I've seen these require a client AND server application to function.

答:
First of all, this sounds like something that you shouldn't be trying to do.

For example, if you have some application on A that calls B which in turn calls C, then it shouldn't be the responsibility of A to figure out why isn't B working. Simply call B and if it doesn't work, then it doesn't work.

Now, if you really want to do this, you would need some service on B that forwards the request to C (or something like that). If you don't want to install anything on B, then the only way is to (ab)use some service that's already installed on it. But I can't think of any common service that would allow you to do this.


问:
Why do ads for s/w engineers always say they "offer a fast-paced environment"?
Who wants to work in a fast-paced environment? Not me! I want a civilized environment where people have a sense of balance. Higher quality work gets done that way and work life isn't full of stress and anguish. </p>

答: Because their Capability Maturity Model is at Level 1 - Chaos.


问:
Emacs-as-OS: obsolete?
In an attempt to reach at least beginner status with such a legendary editor, I have been coding in Emacs for the last two months.  I try to keep an open heart, but I find myself continally disagreeing with one core design choice: that Emacs allow its users to never have to leave.  In a 2010 world, I just think that every side feature of Emacs is hopelessly behind dedicated software:

I would never use its built-in browser; Chrome is years ahead.

I would never use its dired feature; Path Finder (Mac OS X) suits my needs.

I would never use its built-in email; the Gmail web interface has more relevant features like Priority Inbox.

Etc.

Sure, I might occasionally dip into Emacs to use regexps, etc. for one of the above tasks, but other than regexps, I really see no reason to ever touch those side features.  I'm a completely newbie, yet I have a strong gut feeling that Emacs-as-an-OS is obsolete.

Emacs experts, do you think that Emacs' choice to be a comprehensive environment is the right choice for 2010 and the future?  Are there particular peripheral features that are still at or ahead of their time compared to alternatives?

答:
I've been using emacs for the last 10 years (from and to), and I can only say that you are absolutely right. Back in the days, I used gnus and the w3 browser, but clearly they are no longer up to it when compared to dedicated programs. But, obviously, you cannot run Chrome in text mode so this is where emacs wins. And even there, I'd rather use lynx/elinks or mutt for that.

Emacs-the-programmers-editor has lost its touch as well. Text editing is just fine, but when I'm writing code, I find myself wishing for functions like: goto definition, auto completion, refactoring, syntax hints, parameter docs etc etc (think Eclipse). I have tried a couple of emacs modes but never got it to work right. And no, I don't want to learn elisp, thank you.

Also, emacs don't really understand the semantics of the code. This is painfully obvious when coding in a file containing multiple languages like html with javascript and php or something. It just breaks down. For that, I much rather use any other editor (notepad++ or whatever) which does the job much better.

Title: Emacs-as-OS: obsolete?


问:
What Do I Need To Know About Servers In a Web Development Role?
I know that may sound a little vague, so I'll try and explain a little further...

After being self employed developer for many years I'm now in search of a commercial web developer role. My only experience with servers and hosting is uploading through FTP and playing around with CPanel/WHM a little. The role's I'm going for are web development PHP, MySQL, HTML, CSS type roles, but in recent interviews I've been asked questions about setting up things on the server, that I had no idea what was being said... which wasn't ideal!

Without knowing more than I do, it's hard to explain what exactly I'm looking to learn, but it's basically just the server elements I should know as a web developer? If you're a web developer, do you have any dealing with the server apart from uploading files, and if so, what? Are things like Subversion(SVN) and version control systems often set up by the web development team, could that be what they were talking about?

答:
This is a big set of questions, but I suspect one that a lot of folks need to address, particularly as they start to advance in a career that started with a heavy front-end focus.

You mention that you are going for a role that includes PHP and MySQL development.  These are things that need to execute on the server.  Being able to make good technical judgments as a developer requires that you gain an understanding of how these things work on the server and how they interact with the web front-end. So, you clearly need to develop an understanding of the server.

Rather than trying to figure out up front the exact body of knowledge that you might need about the server, I would recommend diving in and building something including installing all of the server side software yourself.  A great way to get your feet wet is to install Linux on your computer.  You can use something like VirtualBox to let it run alongside your current OS. Install MySQL, install and set up the server for PHP and try to get everything working together.  The great thing is, these days, a moderately well equipped laptop can run all of this and be the "server". This could be tough at the beginning, particularly if you don't have experience using Linux and the command line. As a developer, you should at least know enough to be able to get through this exercise and it will give you a jump start in figuring out how to further your knowledge.

There are three areas where you will probably need to get up to speed:

The basics of the Linux operating system. Maybe start with an easy to install distribution like Ubuntu.

Setting up a web server and PHP.  Installing Apache is a good place to start.  There are other alternatives, but this is where most people start.

Learning the basics of installing and running MySQL. At the very least, as a developer, you will probably need to be able to write DDL to create tables and other structures in the database and you will definitely need to be able to query the database on the server to explore data and ensure what your application is spitting out matches what is in the database.

If you were to go with Ubuntu, you could follow the basic instructions here to get yourself up and running.  Note, you will have to do quite a bit of ramp up on Linux basics before starting to install and play with the web servers/database components.

In terms of how developers need to interact with the server, beyond uploading files, I think this varies a lot from organization to organization.

The developers are often dealing with the administration of at least the development environment. Sometimes, it is developers who are setting up the revision control system (for example SVN) and the deployment process (moving code across environments).

To your point, at the very least developers will need to use revision control system that is living on the server.

You will also need to do things like look at the logs on a server to see what messages are being generated to help diagnose and resolve problems.

You may need to work with an infrastructure team to determine things like the network configuration or storage configuration of the server. Often, application issues are a combination of the configuration and the code.

The point is that there is not a single answer for exactly how you will need to touch the server, but in the course of your career, it will certainly go beyond just uploading files via something like FTP.  Getting started by learning the basics now will help.


答:
You need to know below things to complete the web development cycle.

1) IDE (Netbeans and Eclipse etc.)

2) Any programing language for coding. (PHP, java, etc. )

3) Front technology for page designing (HTML, CSS etc.)

4) Backed database to store and retrieve data. (MySQL etc)

3) Version controlling system for checking and retrieve you code form repository.

4) build tool to compile you code with dependent files. (Ant, Maven)

6) Web server to deploy and run you code.

7) Need to know basic deployment process over servers to run and test you web and ejb component. (Tomcat, Web-Logic server)

Title: What Do I Need To Know About Servers In a Web Development Role?

Body:
I know that may sound a little vague, so I'll try and explain a little further...

After being self employed developer for many years I'm now in search of a commercial web developer role. My only experience with servers and hosting is uploading through FTP and playing around with CPanel/WHM a little. The role's I'm going for are web development PHP, MySQL, HTML, CSS type roles, but in recent interviews I've been asked questions about setting up things on the server, that I had no idea what was being said... which wasn't ideal!

Without knowing more than I do, it's hard to explain what exactly I'm looking to learn, but it's basically just the server elements I should know as a web developer? If you're a web developer, do you have any dealing with the server apart from uploading files, and if so, what? Are things like Subversion(SVN) and version control systems often set up by the web development team, could that be what they were talking about?


问:
Deferred Open Source licensing
Are there established models for releasing an initially proprietary piece of software under FLOSS conditions after a defined period or a certain point of time?  The main problem here is that all parties involved must be able to trust that the Open Source licensing will actually take place at the defined time and no party can further defer or cancel this process.

Clearly such a model has its problems, for example it's problematic to deal with contributions from "outside", legally and technically.  Ghostscript is a prominent example where a deferred model has been used and abandoned.  However, if certain parties involved will insist on keeping the software proprietary, at least for a certain period of time, then the only options are a deferred Open Source licensing model or no Open Source licensing at all.

I think I read about services that serve as trusted parties who take care of Open Sourcing the software.  However, I was not successful in spotting any of those.

答:
If the existing license doesn't already permit re-licensing, all copyright owners must agree to re-license an application.  If any of the copyright owners object, then the re-license cannot occur.

Some licenses like BSD or MIT support re-licensing in a fairly straightforward manner.

Commercial / proprietary licenses generally don't permit re-licensing.

If there are multiple copyright owners, it is possible to craft an agreement that effectively says "I agree to re-license my portion of application such-and-such under the terms of some-preferred-OSS-license so long as all other copyright owners agree as well."

Obviously, you need to replace "such-and-such" with the application name, and all of the copyright owners need to agree on a specific open source license.

I would strongly encourage consulting an attorney in order to craft this agreement.  I'm sure there are hiccups that will trip things up if you try to do something informally.

The key is to get everyone to agree to the change if everyone is in agreement but to do so in a way that doesn't irrevocably commit them if an owner resists the change.

Going forward, you should have all contributors assign copyright to the foundation you'll create in order to provide stewardship for the now open source application.  By having a single copyright owner for all new contributions, future license changes will be much easier to implement.

Note that you can insert restrictive clauses into the copyright assignment paperwork that keep the foundation from re-licensing the open-source project as a commercial project.  Again, consult an attorney, but it is possible to provide conditional assignment of copyright.

Title: Deferred Open Source licensing


问:
How can I introduce QA and break it into parts for various people?
I was recently asked how to do this, specifically:

How to introduce QA into an organization?

How to break up QA into parts that others can do ?

How to prioritize what needs QA?

How to determine what to buy? code? etc.

The organization uses Rails on Rails extensively as the development platform

Note:  I am posting a lengthy answer myself but I will also upvote additional good answers (and probably incorporate them into my answer).

答:
1. How to introduce QA into an organization.

Quality Assurance happens at all levels of product development, from code quality to server environments to user experience.  Introducing QA to an organization means looking at all the areas involved and seeing how QA processes and approach can improve the product quality.

2. How to break up QA into parts that others can do ?

OK this is more down to the nitty gritty.
I will break this up into 4 parts:

Code Quality can be achieved using a number of tools and processes:

Standards and Guidelines.  For example for ruby code the Sandi Metz guidelines of 5 lines methods, 100 lines maximum classes, max of 4 parameters, etc.  This will apply directly to the development team members writing the code for features, bugs and chores and should be assured through code review before code acceptance with the developers code review pair person.

Code Quality.  There are a number of tools that can and should be used to improve code quality.  For example in the Ruby space 'reek' is a great tool to look for code smells.  These tools can be used by the development team members and should be used by the code team leader when reviewing code with team members.

Unit Tests for new code.  New code should include unit tests as part of their development and they must be included in all time estimates of how long things take.  Tools that can help out in this area to make sure that the code have coverage include simple_cov, rails_best_practices, rubocop, etc.  As with Code Quality, these tools can be used by the development team members and should be used by the code team leader when reviewing code.

User Experience and Integrated Testing.  This is where the development and deployment teams make sure that the new changes work for the end user and work in all browsers and devices as expected.  There are a number of tools and services that are very helpful in this area, including:

For Ruby, Cucumber is a high-level tool that can be used to put together end-user scenarios.  Cucumber tests are written be the development in close consultation with the product team, using language that reflects the users domain.

For testing in actual browsers the long-term goal is to build up an automated test suite that can be run at will.  The preferred tool for doing this is Selenium.  Selenium tests can be written in two (broad) ways.  Firstly they can be written by developers in the language of their choice.  In practice this is rarely done in smaller organizations.  They can also be developed by using a free Firefox IDE plugin.  This is a great tool for lower level developers to easily write browser based tests.  The developers that use it will need some training on css, xpath, IDE specifics and organization.  Another item to address is how to address their feedback with the development team.  For example how to address "I need a data-attribute on the login username field".  Over time, Selenium tests amass to form a regression suite that makes sure the product works as expected after any changes.  Selenium tests are often the exclusive domain of the QA group and are not developed by the main code developers.

For device/browser testing a great (free) OS emulation tool is Virtual Box which is very helpful for testing ie6, ie7, ie8 and ie9.  Virtual Box would be suitable for any developer wishing to check out 'old browser' views.  In my experience it has been most useful for the QA / Delivery team who need to look at older browsers to be sure the product still works ok.  Obviously devices such as cell phones and ipads should also be checked against and for this there are a number of tools such as iPad Peek, iPhone tester, Mobile Phone Emulator, MobiReady, Responsivepx and Screenfly.  This is a rapidly changing area for products and tools.  There are also external services such as Saucelabs that can help in running testing against multiple devices.

3. How to prioritize what needs QA?

This is where the product and developments team interface.  The product team has a good idea of how the app is used, where it is used, what devices it is used on and the importance and priority of the application functions in relation to the mission of the organization.  The QA team and developers have a better sense of how long it takes to write code and tests in Ruby, Selenium and other tools.  The merging of the two sets of information will drive answers of what to test.

4. How to determine what to buy? code? etc.

When considering Quality and QA processes the main consideration is which parts of the development process to apply these processes to.  For the most part, Quality in software development is mostly about internal processes and approaches.  It's hard and unwieldy to out-source much of this outside of the development team.  This leads to 'build vs. wing-it' rather than 'build vs. buy' decisions.  This also means that the direction and guidance of QA needs to come from management.

The end result should be quality that is 'baked in'.


答:
Focusing on What do you need to know about servers to be a web developer?...

Actually surprisingly little.  Your main areas of knowledge should be programming, html, php, etc.

What you to need to know is how to run things locally and when you do this you are using your box as a 'server'.  So when running locally you use a web browser to view the pages, just as with any internet site... except yours will be http://localhost or http://127.0.0.1

As for configuring cgi, http, etc. I don't expect you need to know that.  You can always work through any general book on setting up a web server for the OS you work in and that would be enough coverage to know the general terms.

For the bigger picture I recommend getting into Linux and learning how to set up and configure machines such as web servers.  But only if you actually have an interest in the stuff.  Not just to impress in interviews.

Finally I would recommend you consider making notes during interviews about areas you don't know enough about.  It would help if your question was more specific  about just which terms, etc. you didn't know.


问:
Ruby - when to use instance variables vs parameters between methods?
I'm writing several methods that call other methods.

To pass the information I have a couple of choices:

Pass the information as parameters

Set instance variables so that other methods can access them

When should I choose one option over the other?

It seems that the first option is good as it is very specific about what is being passed.  the downside seems to be that a lot of values are being passed around.

The second method doesn't require passing all the values around but seems to lead to a lot of magic where methods set instance variables 'somewhere'

Should I always be very explicit about gets passed to other methods in the class?  Are there exceptions so this?

答:
It depends on the role of those variables with respect to the entire class.

If your class is small, and the information that these variables transport is relevant to all or almost all of it, then it makes sense to have them as instance variables. A bank account object probably needs to know its holder for most actions anyway, so it makes sense to hold on to it indefinitely.

If the data are very specific to this method and its helpers, then they should travel as parameters. The date of a transaction is not so much a feature of the account as of a single action taken on that account. (If you have more than one of these parameters, and they tend to be passed around as unit (e.g. date, time of day and time zone), then it is also wise to bundle them into a helper object to keep the number of parameters down.)


答:
Let me misquote you to make my point clear:

I'm writing several functions that call other functions. To pass the information I have two choices:

Pass the info as arguments.

Use global variables.

When should I choose one option over the other?

It is generally acknowledged that non-local state is a bad idea. You should therefore generally pass the information using parameters, not via variables in a common scope. This becomes more manageable if you group related information together into objects or structs.

Passing too many parameters is a code smell, and it can probably be refactored to use a few more classes. Assume a pathological case where you are writing an address book and have a method add_contact(surname, firstname, fullname, ...). It would be better to group that into a Name class, likewise for parts of an address: add_contact(name, address).

If however the necessary parameters to your function are completely unrelated, it may be that your method is trying to do too much, and should be refactored into smaller parts.

I do not think that using instance variables is a good solution: it is needless mutation of state, and brings with it all the problems of global variables, on a smaller scale. This way lies un-debuggable spaghetti code.

Title: Ruby - when to use instance variables vs parameters between methods?

Body:
I'm writing several methods that call other methods.

To pass the information I have a couple of choices:

Pass the information as parameters

Set instance variables so that other methods can access them

When should I choose one option over the other?

It seems that the first option is good as it is very specific about what is being passed.  the downside seems to be that a lot of values are being passed around.

The second method doesn't require passing all the values around but seems to lead to a lot of magic where methods set instance variables 'somewhere'

Should I always be very explicit about gets passed to other methods in the class?  Are there exceptions so this?


问:
When do you say "near ID" / "far ID" when using RTMFP in ActionScript 3?
I've been using RTMFP streaming for around a year in ActionScript 3, and I pretty much know the difference between a near ID and far ID.  The near ID is your peer ID, and the far ID is the other guy's peer ID.

The problem I'm having is that, to my knowledge, choosing whether to use one term or the other in a given sentence is a little like choosing whether to say "go" or "come".  In English, "go" and "come" have opposite meanings, but ironically, they can still be used almost interchangeably.  It's because whether you're going or coming is so heavily dependent on perspective, as opposed to anything concrete.

Is the choice of words between "near ID" and "far ID" just as ambiguous, or is there some sort of method to the madness?  Thanks!

答:
The difference is completely based on perspective: whether you're working from the perspective of a client or the server. I don't think of this as ambiguous, but it can be confusing if you're not clear on your perspective.

For reference, the Flash Media Server 4.5 documentation states:

Client.farID

A String identifying the RTMFP identity of the client. This property has the same value as the ActionScript 3.0 NetConnection.nearID property.

Client.nearID

A String indicating the RTMFP identity of the server to which the client is connected. This property has the same value as the ActionScript 3.0 NetConnection.farID property.


问:
Proper library for enums
I'm trying to refactor some code such that the display is separate from the implementation, and I'm not sure where to put the existing enums.

My project is currently structured as follows:

Utilities

RemoteData (Depends on: Utilities)

LocalData (Depends on: RemoteData, Utilities)

RemoteWeb (Depends on: RemoteData, Utilities)

LocalWeb (Depends on: RemoteData, LocalData, Utilities)

I'm now trying to add "ViewLibrary (Depends on: Utilities)" to this list, and then adding it as a new dependency to both RemoteWeb and LocalWeb.  It will contain a set of interfaces which the other two projects will implement, use to populate the view, and then consume the result.

There's an enum which is currently used in all the projects except Utilities.  It thus lives in the RemoteData project, because everything else depends on it.  But this new ViewLibrary won't depend on either data project.  So how will it know about this enum?

Some options I see:

Create a new project just for shared enum values.

Add it to Utilities, even though it is related to data.

Define it a second time in ViewLibrary, and require both RemoteWeb and LocalWeb to convert the one type into the other when they access the shared views.

Add a dependency on RemoteData to the ViewLibrary, even though it's supposed to be independent of data-source.

Are there any better options?  Is this structure flawed to begin with?

答: In general, you want to put code in libraries that are common to the other libraries in which they will be used, and name them accordingly.  So in your case, since the enum is common only to the RemoteData and LocalData libraries, and specific to this particular project, I would make a new library called [ProjectName]Data and put it there.

Title: Proper library for enums


问:
OpenGL extension vs OpenGL core
I was doubting: I'm writing a cross-platform engine OpenGL C++, I figured out Windows forces the developers to access OpenGL features above 1.1 through extensions.

Now the thing is, on Linux, I know that I can directly access functions if the version supports it through glext.h and opengl version. The problem is that if on Linux, the core doesn't support it, is it possible there is an extensions that supports the same functionality, in my case vertex buffer objects?

I'm doing something like this:

Windows:

```<code>#define glFunction functionpointer_to_the_extension
</code>```

Linux:

Since glext already defined glFunction, I can write in client code glFunction, and compile it both on Windows AND Linux without changing a single line in my client code using the engine (my goal).

Now the thing is, I saw a tutorial use only the extension on Linux, and not checking for the opengl implementation version. If the functionality is available in the core, is it also available as extension (VBO's e.g.)? Or is an extension something you never know is available?

I want to write an engine that is capable of using all the hardware functionalities, so I need to check (on Linux) for extensions as well as core version for possible functionality implementation.

答:
If the functionality is available in the core, is it also available as extension (VBO's e.g.)? Or is an extension something you never know is available?

First, you need to check if the hardware supports the extension (just type glxinfo in terminal, and you'll get list of supported extensions).

The second thing is the driver support. If the driver doesn't support it, it is not going to work.

Title: OpenGL extension vs OpenGL core


答:
In addition to DemetriKots answer, I'd also add looking at solutions for automated deployment and continuous integration. Setting up the server initially is only one step, and deploying over FTP is painful and error prone, with no proper solution for rolling back bad deploys.

Hudson - Continuous integration server

Phing - automated build tool, specifically for PHP, based on Ant

Ant - automated build tool

Capistrano - create deployment scripts to automate and ease deploying your web application.


答:
My first point of advice is to not exclusively limit yourself to any one role.
It's great to be a specialist and have a deep knowledge in a particular skill
set (PHP, for instance). However, it is just as important to have a broad knowledge that spans across the rest of your domain.

In my experience most teams are not looking to hire someone that has the
knowledge to rewrite the core functionality of PHP, but rather someone that
can handle any problem that is thrown at them (although having that level of
knowledge would certainly not hurt). Or at least someone that can help solve
any issues that the team encounters. For instance, imagine a situation where
your application goes down and customers are being affected.  You can either
throw your hands up and say "I have no idea what to do..." or you can SSH into
the server, start scanning logs, notice that the diskspace of a particular
filesystem is full and proceed to clean it out. This is a minor example but I
think the point is clear. With that basic knowledge, as a developer, you
could write a script that monitors that particular filesystem and cleans it
out once it reaches a certain threshold. You have now become that much more
valuable to your manager.

Another thing I have learned during my career, is that things move fast, and
if you don't keep up you are going to be left behind. The more you know about
  your entire environment (including the business aspects) the better off you
  are. That's not to say you need to be an expert in everything you do, but at
  least have the knowledge to not be labeled as clueless. The more familiar
  you are, the more adaptable you are, and the more valuable an asset you are
  to your company.

To specifically answer your questions...

What server elements should I know as a developer?

Be familiar with the entire application stack. Know what web server, database,
caching mechanisms, etc. that are being used. And which versions, too. Have
enough familiarity that you can recreate the environment on your own server.
Which, in and of itself, is vitaly important. You should strive to more or less
have the same environments in development and production, as it reduces
surprises (http://12factor.net/dev-prod-parity).

As a developer what dealings do you have with the server?

This really depends on the team. In my particular case, the developers play a
huge role in staging the environments. We are the most familiar with the inner
workings of the application and so are in the best position to determine what
server technologies are in place to run it. I imagine not all teams have such
a hands on approach, but to have enough familiarity to be able to involve
yourself in the discussions is a great advantage. Specifically, in regards to
version control, you as the developer are highly affected by which technology
is chosen (Git, Subversion, Mercurial, etc.), and therefore should strive to
involve yourself in the decision process.

So, now what?

As for my suggestion as to how best to approach learning all of this? Move
your feet. Don't
worry about trying to read everything you can on the subject, most of it will
probably just leak out of your brain by the time you are finished. Instead
start developing something from the ground up. Start with Vagrant; it will
allow you to easily create and manage a virtual machine that you can use as your
new playground. Then, install a web server and a database and start creating. If
you have an idea for an app, perfect, go for it... if not, find a tutorial or
try to recreate an existing app. The point is just to become familiar with the
entire process. Also, as a PHP developer, be sure to check out PHP: The Right Way... it really contains a lot of excellent info. And most importantly, don't stress yourself out. I imagine you
followed the path of a developer because it's something you enjoy and are
passionate about... don't lose sight of that!


问:
How do I decide to which class a method should belong
I have TopicBusiness.class and PostBusiness.class. I have no problem with deciding into which class methods such as addPostToDatabase() or getAllPostsFromDatabase() should go. But what about getAllPostsFromTopic(TopicEntity topic) or getNumberOfPostsInTopic(TopicEntity topic)?

Should the parameter be the deciding factor? So when the method takes TopicEntity as parameter it should belong to TopicBusiness.class? I am quite puzzled by this.

EDIT:

Some more info as requested. TopicBusiness.class and PostBusiness.class are classes holding all the business logic of the application concerning topics and posts respectively - that is fetching the data from database and/or performing some operations on them.

TopicEntity is data (in this case representing single topic) fetched from database. getAllPostFromTopic(TopicEntity topic) gets all posts from database that belong to particular topic, while getNumberOfPostsInTopic(TopicEntity topic) performs database query and returns the number of posts that topic passed as parameter consists of.

答:
I wouldn't say parameter, but basically yes.

Number of posts is a property of a topic, as are the posts in the topic.

Consider the NNTP References header for a real world example.  A post (message) knows about it's direct parents.  But it doesn't know about it's siblings or children.  This is of course mandated in the case of NNTP because it is a distributed system, and in a non-distributed system you could in theory make each post have a reference to every other post in the topic.  But doing so doesn't actually help because it doesn't help with the model, which is typically a tree.

To decide where things go, model what they are logically a part of.


问:
Storing large data in HTTP Session (Java Application)
I am asking this question in continuation with http-session-or-database-approach.

I am planning to follow this approach.

When user add product to cart, create a Cart Model, add items to cart and save to DB.

Convert Cart model to cart data and save it to HTTP session.

Any update/ edit update underlying cart in DB and update data snap shot in Session.

When user click on view cart page, just pick cart data from Session and display to customer.

I have following queries regarding HTTP Session

How good is it to store large data (Shopping Cart) in Session?

How scalable this approach can be ? (With respect to Session)

Won't my application going to eat and demand a lot of memory?

Is my approach is fine or do i need to consider other points while designing this?

Though, we can control what all cart data should be stored in the Session, but still we need to have certain information in cart data being stored in session?

答:
I think the general pattern is try to store the least information possible in memory, only store the useful data only. This approach would make your application scalable.

If you really want an scalable application, you should build it on an app server, like JBoss/Wildfly or any other Java EE Container.

Design considerations in Java EE is to keep session beans as light as possible.


问:
Why don't research papers that mention custom software release the source code?
Is there a reason why the source code of software mentioned in research papers is not released? I understand that research papers are more about the general idea of accomplishing something than implementation details, but I don't get why they don't release the code.

For example, this paper ends with:

Results

The human line drawing system is implemented through the Qt framework in C++ using OpenGL, and runs on a 2.00 GHz Intel dual core processor workstation without any additional hardware assistance. We can interactively draw lines while the system synthesizes the new path and texture.

Do they keep the source code closed intentionally because of a monetization they intend to make with it, or because of copyright ?

答:
Most of the reasons I can think of have already been raised here, but I thought I would add two more that actually happened to me:

The journal has no idea what to do.

For one of the papers I was working on, I decided that I was absolutely, without question going to include the source code (the whole point of the paper was data visualization) and example data to go along with it. So along with the submission I attached Electronic Supplements 1 and 2 - an R script with my code, and a CSV file with the data needed for said R script.

The journal, as it turns out, can only take electronic supplements if they've been shoehorned into Word files. After trying for the better part of a day to get the R script in that form, I gave up and decided not to include the code as a supplement. I could have hosted it at my University, but as a graduate student I knew that I was going to lose my account there in ~1 year - open source isn't of any use if its immediately overtaken with linkrot.

I ended up hosting it on GitHub and putting a reference to that in the paper, but that was because I really wanted the code to go in. I can see, especially since most people in my field don't use something like GitHub, just deciding that the effort wasn't going to be worth the handful of people who would download it, and who could email me anyway if they really want to.

The journal just isn't interested

I inserted some small details about the code itself into a paper on request from a reviewer, but its a clinical journal (read: no one codes), it doesn't allow electronic supplements, and again, adding the source code would likely have been more trouble than it was worth.

Ironically, if anyone did go looking for the code, it is (or soon will be) open source, but I was already running on the edge of 'This is growing distractingly technical' and I decided that the brief, 'make the reviewer happy' mention was all I was going to do.


问:
Is it acceptable to upload offensive content to GitHub?
I developed an offensive content checker for my website and want to publish it on GitHub. However, the source code contains many offensive, racist and otherwise nasty content.

The source is fully documented, but I wanted your opinion on whether it's acceptable to publish such work on GitHub or whether to leave the array of strings up to the imagination of the reader?!

答:
"All problems in computer science can be solved by another level of indirection." (by David Wheeler).

Your options aren't limited to either uploading it or not, if you take into account that you can encode content so that it won't bother readers.

As an example, simply shifting to the next letter (A to B, B to C, etc., with Z shifting to A to complete encoding) can turn famous four letter words into totally harmless Gvdl. All you need to use it in your application would be to shift it back in the opposite direction, to previous letters, with A shifting to Z.

As pointed out in comments, an approach like the above is used in ROT13 letter substitution cipher, known for its use "as a means of hiding... offensive materials from the casual glance..."

For the sake of completeness, consider additionally running your checker against an encoded dictionary, in order to ensure that the chosen encoding didn't accidentally turn one offensive word into another.

When encoding stuff like that, it makes sense to double check, because one can't reliably predict things. In one of my past projects, we had a fairly severe mail outage when a misconfigured checker began discovering offensive content in random sequences of characters (in the uuencoded content of ZIP archives).

Compared to passing around plain text, Gvdls, encoding has a substantial benefit of fully avoiding legal issues and all the involved risks and dependencies.

Just think of it. Say, particular terms of service at a particular repository allow my content, fine.

But, what if they decide to change the TOS? Or, what if I decide to change to another repository, having incompatible terms. What am I going to do?

Note by the way that even being at a "friendly" repository, here and now, still isn't fully safe.

What if someone won't be able to download my content because of weird web filter? Am I willing to respond to user complaints and explain how to fix the filter? Their filter...

...You see, I would rather think twice before I decide against encoding. And even if I decide, I would make sure that I have a very, very good reason for that.


答:
As a Topic can have multiple Posts, the TopicEntity.class should know what and how many PostEntitys it has, so Topics could have a getPosts() method instead of using another method which uses TopicEntity as parameter.

However if you need such a method for special purposes I'd say:

The method belongs to that business class which the result is belonging to.

On the concrete example this means:

getAllPostsFromTopic(TopicEntity topic) gets PostEntities, and getNumberOfPostsInTopic(TopicEntity topic) gets information about a subset of Posts, so both clearly belong to PostBusiness.class.

This is also intended by the choise of the methods names:

getAllPostsWhichAreOf(predicate)

getNumberOfPostsWhichAreOf(predicate)

Title: How do I decide to which class a method should belong

Body:
I have TopicBusiness.class and PostBusiness.class. I have no problem with deciding into which class methods such as addPostToDatabase() or getAllPostsFromDatabase() should go. But what about getAllPostsFromTopic(TopicEntity topic) or getNumberOfPostsInTopic(TopicEntity topic)?

Should the parameter be the deciding factor? So when the method takes TopicEntity as parameter it should belong to TopicBusiness.class? I am quite puzzled by this.

EDIT:

Some more info as requested. TopicBusiness.class and PostBusiness.class are classes holding all the business logic of the application concerning topics and posts respectively - that is fetching the data from database and/or performing some operations on them.

TopicEntity is data (in this case representing single topic) fetched from database. getAllPostFromTopic(TopicEntity topic) gets all posts from database that belong to particular topic, while getNumberOfPostsInTopic(TopicEntity topic) performs database query and returns the number of posts that topic passed as parameter consists of.


问:
UI design and confirmation paradigm
I just saw this lecture by Spolsky, where he questions the need for choices and confirmation dialogs. At some point he has a MacOS settings window and he mentions that "now some are getting rid of the OK button". The window indeed has no OK (or cancel) button. Changing a setting makes it change, when you're done configuring, you close that window, period.

Being a long time Windows user and a recent Mac owner, the difference is noticeable at first. I looked for the OK button for a while, only to find out, quite naturally and painlessly, that there was none. I expressed satisfaction and went on my merry way.

However, I'm curious to know if this UI design pattern would succeed in the Windows-based world. Granted that if Microsoft brought it out with say Windows-8 (fat chance, I know), people would get used to it eventually. But is there some experience out there of such an approach, of changing the "confirmation paradigm" on a platform where it's so prevalent? Did it leave users (especially the non-technical ones) confused, frustrated, scared, or happy?

TL;DR: Remove OK/cancel confirmation, what happens?

EDIT:

Mac GUI for appearance settings.

答: I find a nice middle ground is when some text is temporarily displayed (not in a pop-up) saying "your change has been successfully saved" or something similar to Google Doc's auto-saving

Title: UI design and confirmation paradigm


问:
What am I risking if I don't update my SDK/JDK and bundled runtime/JRE every time there's a security update?
It seems like there's a new major security hole patched in Java every other week, and I would assume the same goes for other development platforms.  After years of frustration trying to get customers to install and configure a compatible JRE on their systems, we started bundling one with our software.  (By bundling, I mean we extract a copy of the JRE in our installation directory--we don't install the JRE and configure it as the system default.)

The problem is, it's a hassle having to keep that JRE up-to-date because first we have to retest everything to make sure the update didn't break anything (it has broken some of our third-party dependencies in the past).

How seriously, if at all, are we putting our customers at risk if we don't update our SDK/JDK and the runtime/JRE that we bundle with our product every time there's a security update?  Is it reasonable to just update on a periodic schedule--say, once every 6 months or so?

答:
That depends on the nature of the security holes and that of your application.

The most popular and major ones that have been fixed are related to applets. This is to say that there's some hole in the Java stack (JVM, native libraries, Java libraries, etc.) that allows an applet to access e.g. files on disk, to run a process, the kind of things that applets shouldn't be able to do.

If your application is a desktop application, I believe there is very little risk involved for a 6 months update interval. Most of the times, the kind of holes in desktop applications is tied to operating system holes, such as allowing a lower privilege application access a window from a higher privilege one. Or similarly, an application running in non-administrator being able to access an administrator's application windows and process address space.

On the other hand, another application that the user runs with as much privilege as yours can do just about anything. Messing around with your application is not really the worse of things I can imagine, unless it can launch missiles or withdraw money.

EDIT: If your application is a server, then again some of the nasty vulnerabilities might pose a greater risk. We never know. Maybe there's something in Java's sockets that allows remote code execution, and so you'd consider this to be very high risk compared to delegating the update burden to your client.


问:
Perfomance of 8 bit operations on 64 bit architechture
I am usually a Python / Database programmer, and I am considering using C for a problem.

I have a set of sequences, 8 characters long with 4 possible characters. My problem involves combining sets of these sequences and filtering which sets match a criteria. The combinations of 5 run into billions of rows and takes around an hour to run.

So I can represent each sequence as 2 bytes.

If I am working on a 64 bit architechture will I gain any advantage by keeping these data structures as 2 bytes when I generate the combinations, or will I be as well storing them as 8 bytes / double ? (64 bit = 8 x 8)

If I am on a 64 bit architecture, all registers will be 64 bit, so in terms of operations that shouldn´t be any faster (please correct me if I am wrong).

Will I gain anything from the smaller storage requirements - can I fit more combinations in memory, or will they all take up 64 bits anyway?

And finally, am I likley to gain anything coding in C. I have a first version, which stores the sequence as a small int in a MySQL database. It then self joins the tabe to itself a number of times in order to generate all the possible combinations. The performance is acceptable, depending on how many combinations are generated. I assume the database must involve some overhead.

答:
You are likely to optimize for the wrong case. Remember the two golden rules of optimization:

Premature optimization is the root of all evil.

No optimizing without profiling.

As 48 = 65536 is significantly less than your ”billions of combinations”, I doubt you are going to run into performance issues regardless of the programming language you are using. Have you prototyped this in Python? Is it not fast enough? If you do want to optimize that, try to find an algorithm that doesn't even create unwanted combinations.

The advantage of representing a single combination as an integer (for now, size is irrelevant), is that you can iterate through all combinations by simply incrementing that integer. This is going to be fast regardless of language. Note that floating point numbers are not useful here! In C, you could use an uint16_t or larger in this scenario. You need a separate termination condition regardless of the type you are using.

How many bits any type actually takes up in memory is subject to alignment. You should only worry about this after re-reading the two above optimization rules, because your compiler will know more about alignment than you.


答:
I have to disagree with the ROT-13 solution.  Obfuscating your banned words simply because the sight of them might offend someone is a waste of time.

Your dictionary of bad words/bad-word-rules should come from a separate file anyways (which could be loaded at runtime, or embedded as a resource).  Obfuscating this file simply makes it more difficult for you/other developers/your users to alter it, or fix any issues.  Besides, if I saw a file called "banned_words.txt" on my hard-drive, I would expect it to contain a list of offensive words.

Title: Is it acceptable to upload offensive content to GitHub?

Body:
I developed an offensive content checker for my website and want to publish it on GitHub. However, the source code contains many offensive, racist and otherwise nasty content.

The source is fully documented, but I wanted your opinion on whether it's acceptable to publish such work on GitHub or whether to leave the array of strings up to the imagination of the reader?!


问:
How to manage a lot of Action Listeners for multiple buttons
I have this Tic Tac Toe game and I thought of this really cool way to draw out the grid of 9 little boxes. I was thinking of putting buttons in each of those boxes.

How should I give each button (9 buttons in total) an ActionListener that draws either an X or O?

Should they each have their own, or should I do some sort of code that detects turns in this? Could I even do a JButton Array and do some for loops to put 9 buttons. So many possibilities, but which one is the most proper?

Code so far:

```<code>import javax.swing.*;

import java.awt.event.*;
import java.awt.*;
public class Board extends JPanel implements ActionListener{
public Board(){
    Timer timer = new Timer(25,this);
    timer.start();
}
@Override
protected void paintComponent(Graphics g){
    for(int y = 0; y < 3; y++){
        for(int x = 0; x < 3; x++){
                g.drawRect(x*64, y*64, 64, 64);
        }
    }
}
public void actionPerformed(ActionEvent e){
    repaint();
}
}
</code>```

答:
Create a Square class that extends either a JButton or a JPanel that contains a JButton.  You can put code in there to handle a button press and draw the button.  Use 9 of these in a grid to put on your Board class.

An actual button press should not affect the Square/button directly.  It should call a method on the board class that will check that the move is legal and do any other bookkeeping.  (Admittedly there isn't really much to do here, but your game might get more complicated someday.)  The Board method should also call a Square method that lets the button know it is pushed and causes it to get redrawn.

In summary, handle everything to do with a square/button in a Square class and everything to do with the whole game in the Board class.  Your ultimate goal should be to keep everything as simple as possible and as easy to change as possible.


问:
Writing the minimum code to pass a unit test - without cheating!
When doing TDD and writing a unit test, how does one resist the urge to "cheat" when writing the first iteration of "implementation" code that you're testing?

For example:

Let's I need to calculate the Factorial of a number.  I start with a unit test (using MSTest) something like:

```<code>[TestClass]
public class CalculateFactorialTests
{
    [TestMethod]
    public void CalculateFactorial_5_input_returns_120()
    {
        // Arrange
        var myMath = new MyMath();
        // Act
        long output = myMath.CalculateFactorial(5);
        // Assert
        Assert.AreEqual(120, output);
    }
}
</code>```

I run this code, and it fails since the CalculateFactorial method doesn't even exist.  So, I now write the first iteration of the code to implement the method under test, writing the minimum code required to pass the test.

The thing is, I'm continually tempted to write the following:

```<code>public class MyMath
{
    public long CalculateFactorial(long input)
    {
        return 120;
    }
}
</code>```

This is, technically, correct in that it really is the minimum code required to make that specific test pass (go green), although it's clearly a "cheat" since it really doesn't even attempt to perform the function of calculating a factorial.  Of course, now the refactoring part becomes an exercise in "writing the correct functionality" rather than a true refactoring of the implementation.  Obviously, adding additional tests with different parameters will fail and force a refactoring, but you have to start with that one test.

So, my question is, how do you get that balance between "writing the minimum code to pass the test" whilst still keeping it functional and in the spirit of what you're actually trying to achieve?

答:
When you've written only one unit test, the one-line implementation (return 120;) is legitimate.  Writing a loop calculating the value of 120 - that would be cheating!

Such simple initial tests are a good way to catch edge cases and prevent one-off errors.  Five actually isn't the input value I'd start with.

A rule of thumb that could be useful here is: zero, one, many, lots.  Zero and one are important edge cases for the factorial.  They can be implemented with one-liners.  The "many" test case (e.g. 5!) would then force you to write a loop.  The "lots" (1000!?) test case could force you to implement an alternative algorithm to handle very large numbers.


问:
Is an event loop just a for/while loop with optimized polling?
I'm trying to understand what an event loop is. Often the explanation is that in an event loop, you do something until you're notified that an event has occurred. You then handle the event and continue doing what you were doing before.

To map the above definition with an example. I have a server which 'listens' in a event loop, and when a socket connection is detected, the data from it gets read and displayed, after which the server resumes/starts listening as it did before.

However, this event happening and us getting notified 'just like that' are to much for me to handle. You can say: "It's not 'just like that' you have to register an event listener". But what's an event listener but a function which for some reason isn't returning. Is it in it's own loop, waiting to be notified when an event happens? Should the event listener also register an event listener? Where does it end?

Events are a nice abstraction to work with, however just an abstraction. I believe that in the end, polling is unavoidable. Perhaps we are not doing it in our code, but the lower levels (the programming language implementation or the OS) are doing it for us.

It basically comes down to the following pseudo code which is running somewhere low enough so it doesn't result in busy waiting:

```<code>while(True):
    do stuff
    check if event has happened (poll)
    do other stuff
</code>```

This is my understanding of the whole idea, and I would like to hear if this is correct. I'm open in accepting that the whole idea is fundamentally wrong, in which case I would like the correct explanation.

答:
Not all events triggers are handled in loops. The way I often write my own event engines would be like this:

```<code>interface Listener {
    void handle (EventInfo info);
}

List<Listener> registeredListeners

void triggerEvent (EventInfo info) {
    foreach (listener in registeredListeners) { // Memo 1
        listener.handle(info) // the handling may or may not be synchronous... your choice
    }
}

void somethingThatTriggersAnEvent () {
    blah
    blah
    blah
    triggerEvent(someGeneratedEventInfo)
    more blah
}
</code>```

Note that although Memo 1 is on a loop, the loop is for notifying each listener. The event trigger itself is not necessarily in a loop.

In theory, OS-level key events can use the same technique (though I think they often do polling instead? I'm just speculating here), provided the OS exposes some sort of registerListener API.

Body:
Not all events triggers are handled in loops. The way I often write my own event engines would be like this:

interface Listener {
    void handle (EventInfo info);
}

List<Listener> registeredListeners

void triggerEvent (EventInfo info) {
    foreach (listener in registeredListeners) { // Memo 1
        listener.handle(info) // the handling may or may not be synchronous... your choice
    }
}

void somethingThatTriggersAnEvent () {
    blah
    blah
    blah
    triggerEvent(someGeneratedEventInfo)
    more blah
}

Note that although Memo 1 is on a loop, the loop is for notifying each listener. The event trigger itself is not necessarily in a loop.

In theory, OS-level key events can use the same technique (though I think they often do polling instead? I'm just speculating here), provided the OS exposes some sort of registerListener API.