问:
Is this a valid implementation of the repository pattern?
I've been reading up about the repository pattern, with a view to implementing it in my own application. Almost all examples I've found on the internet use some kind of existing framework rather than showing how to implement it 'from scratch'. Here's my first thoughts of how I might implement it - I was wondering if anyone could advise me on whether this is correct?

I have two tables, named CONTAINERS and BITS. Each CONTAINER can contain any number of BITs. I represent them as two classes:

```<code>class Container{
    private $bits;
    private $id;
    //...and a property for each column in the table...

    public function __construct(){
        $this->bits = array();
    }

    public function addBit($bit){
        $this->bits[] = $bit;
    }

    //...getters and setters...
}

class Bit{
    //some properties, methods etc...
}
</code>```

Each class will have a property for each column in its respective table. I then have a couple of 'repositories' which handle things to do with saving/retrieving these objects from the database:

```<code>//repository to control saving/retrieving Containers from the database
class ContainerRepository{

    //inject the bit repository for use later
    public function __construct($bitRepo){
        $this->bitRepo = $bitRepo;
    }

    public function getById($id){
        //talk directly to Oracle here to all column data into the object

        //get all the bits in the container
        $bits = $this->bitRepo->getByContainerId($id);
        foreach($bits as $bit){
            $container->addBit($bit);
        }

        //return an instance of Container
    }

    public function persist($container){
      //talk directly to Oracle here to save it to the database
        //if its ID is NULL, create a new container in database, otherwise update the existing one

        //use BitRepository to save each of the Bits inside the Container
        $bitRepo = $this->bitRepo;
        foreach($container->bits as $bit){
            $bitRepo->persist($bit);
        }
    }
}

//repository to control saving/retrieving Bits from the database
class BitRepository{
    public function getById($id){}
    public function getByContainerId($containerId){}
    public function persist($bit){}
}
</code>```

Therefore, the code I would use to get an instance of Container from the database would be:

```<code>$bitRepo = new BitRepository();
$containerRepo = new ContainerRepository($bitRepo);
$container = $containerRepo->getById($id);
</code>```

Or to create a new one and save to the database:

```<code>$bitRepo = new BitRepository();
$containerRepo = new ContainerRepository($bitRepo);

$container = new Container();
$container->setSomeProperty(1);
$bit = new Bit();
$container->addBit($bit);
$containerRepo->persist($container);
</code>```

Can someone advise me as to whether I have implemented this pattern correctly? Thanks!

答:
I think you are doing more of a Data Mapper, and as such, it seems correct to me.

In a strict DDD (Domain driven design) point of view, the Repository pattern is one of the most misunderstood/misused patterns. In many examples you will find online, the "repository" is implemented as a database abstraction layer, often implemented with an ORM. However, in a DDD context, a Repository is a collection of Aggregates, not belonging in the data access layer, but in the domain/business logic layer of the application. An Aggregate encapsulates a cluster of objects in order to protect it's invariants, exposing only it's root entity (check this question for more details: https://stackoverflow.com/questions/1958621/whats-an-aggregate-root).

I would "forget" about the Repository pattern and take a look at CQRS (Command Query Responsibility Segregation) instead. If your application contains complex business logic, it might be a good idea to implement it with the tactical patterns of DDD though.


问:
API always returns JSONObject or JSONArray Best practices
I'm making an API that will return data in JSON.

I also wanted on client side to make an utility class to call this API.

Something like :

```<code>JSONObject sendGetRequest(Url url);
JSONObject sendPostRequest(Url url, HashMap postData);
</code>```

However sometimes the API send back array of object [{id:1},{id:2}]

I now got four choices ():

Make the method test for JSONArray or JSONObject and send back an Object that I will have to cast in the caller

Make a method that returns JSONObject and one for JSONArray (like sendGetRequestAndReturnAsJSONArray)

Make the server always send Arrays even for one element

Make the server always send Objects wrapping my Array

I going for the two last methods since I think it would be a good thing to force the API to send consistent type of data.

But what would be the best practice (if one exist).

Always send arrays? or always send objects?

答:
That should depend on what it is actually doing. If it is retrieving one or more objects, it makes logical sense to always return an array containing the results, even if it is an array with only one element. This makes it easy to then do a foreach on the returned array, for example.

If the format of the request causes it to return completely different kinds of data though, it would be clearer to have a different method for each context.

How this would work as a method is a good analogy. If you have some collection foo, and a function searchFoo that searches the collection for elements, you are not going to write it such that it returns an element if only one element matches, and otherwise it returns a list of elements. Either it always only finds one elements (like if the search is based on a unique key) in which case it also returns an object of the appropriate type, or it will find a variable number of elements in which case it will always return a list, regardless of how many elements were found.

ContentLicense: CC BY-SA 3.0


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

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

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

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

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

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

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

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

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

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

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

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

My question regarding this design is rather specific:

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

My question is split into two:

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

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

答:
I think the fundamental problem with your design is that you're introducing a new type for each way to combine your data types and on top of that making the structure of your songs private.

Imagine if I were making a math library, and I had a type for "simple integers" which are just literals. And then I created a separate type "added integers" for the sum of two simple integers. And then a separate type "multiplied integers" for the multiplication of two added integers. Now on top of that I keep the bit pattern that makes up the numbers a secret so the only mathematical operations that'll ever be possible are the ones hard-coded into my library. That's what you're doing.

I think you could achieve what you want by representing everything as (preferably immutable) sequences of chords and making that sequence public. You can re-implement your generators as plain old functions that duplicate, transform, and glue sequences of chords in particular ways. Alternatively, songs could be lazily-produced streams of chords, which would allow you to generate infinite songs. Either design ends up much simpler and there's no limit to the number of ways you can compose songs.

Title: Requesting feedback on my OO design


问:
Prepared statement alternatives for this middle-man program?
I have an program that is using a prepared statement to connect and write to a database working nicely, and now need to create a middle-man program to insert between this program and the database. This middle-man program will actually write to multiple databases and handle any errors and connection issues.

I would like advice as to how to replicate the prepared statements such as to create minimal impact to the existing program, however I am not sure where to start. I have thought about creating a "SQL statement class" that mimics the prepared statement, only that seems silly.

The existing program is in Java, although it's going to be networked anyways so I would be open to writing it in just about anything that would make sense. The databases are currently MySQL, although I would like to be open to changing the database type in the future.

My main question is what should the interface for this program look like, and does doing this even make sense?

A distributed DB would be the ideal solution, but they seem overly complex and expensive for my needs. I am hoping to replicate the main functionality of a distributed DB via this middle-man. I am not too familiar with sql-based servers distributing data (or database in general...) - perhaps I am fighting an uphill battle by trying to solve it via programming, but I would like to make an attempt at least.

答:
Ideally, the interface for your program-in-the-middle would look as similar as possible to your existing program's interface to the database. You might want to start by building a layer in your existing program that interacts with the database, and all other components in your program interact with the database by calling the functions in this new layer. Then you can start separating this layer into a separate library.

If necessary, build a new program around this library that can be called by a web service, or some other messaging method. You could also build a separate layer in the old program that matches the old interface that your original program calls, and this new code will call any new service/messaging system to connect to the new program-in-the-middle.

The program-in-the-middle can use prepared statements or anything else. It shouldn't matter to the original program how the new middle-program interacts with the database, as long as it works.


问:
Passing functions into other functions as parameters, bad practice?
We've been in the process of changing how our AS3 application talks to our back end and we're in the process of implementing a REST system to replace our old one.

Sadly the developer who started the work is now on long term sick leave and it's been handed over to me. I've been working with it for the past week or so now and I understand the system, but there's one thing that's been worrying me. There seems to be a lot of passing of functions into functions. For example our class that makes the call to our servers takes in a function that it will then call and pass an object to when the process is complete and errors have been handled etc.

It's giving me that "bad feeling" where I feel like it's horrible practice and I can think of some reasons why but I want some confirmation before I propose a re-work to system. I was wondering if anyone had any experience with this possible problem?

答:
They're not just used for functional programming. They can also be known as callbacks:

A callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback or it might happen at later time, as in an asynchronous callback.

Think about asynchronous code for a second. You pass in a function that, for example, sends data to the user. Only when the code has completed do you invoke this function with the result of the response, which the function then uses to send the data back to the user. It's a mindset change.

I wrote a library that retrieves Torrent data from your seedbox. You are using a non-blocking event loop to execute this library and get data, then return it to the user (say, in a websocket context). Imagine you have 5 people connected in this event loop, and one of the requests to get someone's torrent data stalls. That will block the whole loop. So you need to think asynchronously and use callbacks - the loop keeps running and the "giving the data back to the user" only runs when the function has finished execution, so there's no waiting for it. Fire and forget.


答:
Try to think in a big problem its always complicated, i try to focus in a small part, you say:

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

I see a lack of abstraction that generates duplication, you can think in the problem in other way:

"Melody is composed of an array of playable objects. Invoking play on it plays these playable objects one after the other"

You don't need two different classes (melody and structuredMelody) to do the same thing. The melody generators can take care of composing the melody with the right "pieces".

Probably with the same approach you can simplify a lot the rest of the system.

Title: Requesting feedback on my OO design

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

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

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

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

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

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

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

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

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

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

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

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

My question regarding this design is rather specific:

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

My question is split into two:

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

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


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

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

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

答:
Find a simple task you can do that does take a half hour or less. Update some documentation, refactor a test or two, fiddle with your dev environment config, or shoot off a few emails.

Basically, there are always dozens of tasks I put off because the big stuff takes priority. But I know they'll never happen if I don't make a little time for them.

ContentLicense: CC BY-SA 2.5

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


问:
How can if (sscanf(buf, "%i", &mode) != 1 || TRUE) be rewritten to if (TRUE)?
I got lost in the opening of this post on reddit.

How can if (sscanf(buf, "%i", &mode) != 1 || TRUE) be rewritten to if (TRUE)?  Does this assume that the sscanf never fails?

答:
Using truth tables, you can show it will always return -EINVAL, thus,  don't even need the

```<code>if (TRUE)
   return -EINVAL;
</code>```

it could be just

```<code>return -EINVAL
</code>```

FWIW, since I don't have the context, this is almost certainly a bug. The

```<code>(mode != 2 || mode != 1)
</code>```

probably should have been

```<code>(mode != 2 && mode != 1)
</code>```

Body:
Using truth tables, you can show it will always return -EINVAL, thus,  don't even need the

if (TRUE)
   return -EINVAL;

it could be just

return -EINVAL

FWIW, since I don't have the context, this is almost certainly a bug. The

(mode != 2 || mode != 1)

probably should have been

(mode != 2 && mode != 1)


问:
Naming boolean field that is a verb
In Java, by convention getter and setter for boolean fields will be isField() and setField(). This works perfectly fine with field names that are adjectives like active, visible, closed, etc.

But how do I name a field that has meaning of a verb, like haveChildren? Add “_ing” to the verb (havingChildren), maybe?

To clarify, I don't have control of the method names (getter and setter) as they are auto-generated by the IDE. So what I need is an appropriate field name so that when the IDE generate a getter for it, it make senses. For example, hasChildren is a perfect field name, but when the IDE generate the getter for the field it would be isHasChildren. How do I solve this?

答:
The question is perfectly reasonable. Sometimes renaming the auto-generated method is not enough. Example: JSF managed beans are expected to have isXyz() as the getter method of a boolean xyz property.

I agree with BlackPanther who suggests renaming the field to parent and using isParent as the method name. Per the information hiding principle, getter and setter methods' readability is more important than the attribute's.

Title: Naming boolean field that is a verb


问:
Is this method pure?
I have the following extension method:

```<code>    public static IEnumerable<T> Apply<T>(
        [NotNull] this IEnumerable<T> source,
        [NotNull] Action<T> action)
        where T : class
    {
        source.CheckArgumentNull("source");
        action.CheckArgumentNull("action");
        return source.ApplyIterator(action);
    }

    private static IEnumerable<T> ApplyIterator<T>(this IEnumerable<T> source, Action<T> action)
        where T : class
    {
        foreach (var item in source)
        {
            action(item);
            yield return item;
        }
    }
</code>```

It just applies an action to each item of the sequence before returning it.

I was wondering if I should apply the Pure attribute (from Resharper annotations) to this method, and I can see arguments for and against it.

Pros:

strictly speaking, it is pure; just calling it on a sequence doesn't alter the sequence (it returns a new sequence) or make any observable state change

calling it without using the result is clearly a mistake, since it has no effect unless the sequence is enumerated, so I'd like Resharper to warn me if I do that.

Cons:

even though the Apply method itself is pure, enumerating the resulting sequence will make observable state changes (which is the point of the method). For instance, items.Apply(i => i.Count++) will change the values of the items every time it's enumerated. So applying the Pure attribute is probably misleading...

What do you think? Should I apply the attribute or not?

答:
In my opinion, the fact that it receives an Action (and not something like PureAction) makes it not pure.

And I even disagree with Eric Lippert. He wrote this "()=>{} is convertible to Action, and it's a pure function. It's outputs depend solely on its inputs and it has no observable side effects".

Well, imagine that instead of using a delegate the ApplyIterator was invoking a method named Action.

If Action is pure, then the ApplyIterator is pure too. If Action is not pure, then the ApplyIterator can't be pure.

Considering the delegate type (not the actual given value), we don't have the guarantee that it will be pure, so the method will behave as a pure method only when the delegate is pure. So, to make it really pure, it should receive a pure delegate (and that exists, we can declare a delegate as [Pure], so we can have a PureAction).

Explaining it differently, a Pure method should always give the same result given the same inputs and should not generate observable changes. ApplyIterator may be given the same source and delegate twice but, if the delegate is changing a reference-type, the next execution will give different results.
Example: The delegate does something like item.Content += " Changed";

So, using the ApplyIterator over a list of "string containers" (an object with a Content property of type string), we may have these original values:

```<code>Test

Test2
</code>```

After the first execution, the list will have this:

```<code>Test Changed

Test2 Changed
</code>```

And this the 3rd time:

```<code>Test Changed Changed

Test2 Changed Changed
</code>```

So, we are changing the contents of the list because the delegate is not pure and no optimization can be done to avoid executing the call 3 times if invoked 3 times, as each execution will generate a different result.

Title: Is this method pure?

Body:
In my opinion, the fact that it receives an Action (and not something like PureAction) makes it not pure.

And I even disagree with Eric Lippert. He wrote this "()=>{} is convertible to Action, and it's a pure function. It's outputs depend solely on its inputs and it has no observable side effects".

Well, imagine that instead of using a delegate the ApplyIterator was invoking a method named Action.

If Action is pure, then the ApplyIterator is pure too. If Action is not pure, then the ApplyIterator can't be pure.

Considering the delegate type (not the actual given value), we don't have the guarantee that it will be pure, so the method will behave as a pure method only when the delegate is pure. So, to make it really pure, it should receive a pure delegate (and that exists, we can declare a delegate as [Pure], so we can have a PureAction).

Explaining it differently, a Pure method should always give the same result given the same inputs and should not generate observable changes. ApplyIterator may be given the same source and delegate twice but, if the delegate is changing a reference-type, the next execution will give different results.
Example: The delegate does something like item.Content += " Changed";

So, using the ApplyIterator over a list of "string containers" (an object with a Content property of type string), we may have these original values:

Test

Test2

After the first execution, the list will have this:

Test Changed

Test2 Changed

And this the 3rd time:

Test Changed Changed

Test2 Changed Changed

So, we are changing the contents of the list because the delegate is not pure and no optimization can be done to avoid executing the call 3 times if invoked 3 times, as each execution will generate a different result.


问:
Replaceable parameter syntax meaning
Replaceable parameter syntax for the console object in C#.

I am taking the O'Reilly C# Course 1 and it is asking for a replaceable parameter syntax and it is not very clear on what that means.  Currently I used this:

```<code>double trouble = 99999.0009;
double bubble = 11111.0001;
Console.WriteLine(trouble * bubble);
</code>```

Am I missing the meaning of replaceable parameter syntax?
Can someone provide an example for what I am looking for?

Original question for the quiz:
"Create two variables, both doubles, assign them numbers greater than 10,000, and include a decimal component. Output the result of multiplying the numbers together, but use replaceable parameter syntax of the Console object, and multiply the numbers within the call to the Console.WriteLine() method."

答:
You're quite right that it's not very clear, and the reason it's not very clear is that O'Reilly are taking liberties with their terminology. It's the kind of thing that only makes sense if you already know what they mean. And this is a course?

Probably the most commonly used overload of string.Format is the one that takes two parameters: a format string and an object array. You've probably used it to format a string with data from other variables:

```<code>int myNum = 123;
string message = string.Format("The number is {0}", myNum);
</code>```

One of the Console.WriteLine() overloads takes these same two parameters, and for the same purpose:

```<code>Console.WriteLine("The number is {0}", myNum);
</code>```

Microsoft tell us these markers in the string ({0}, {1} etc) are

indexed placeholders, called format items, that correspond to an
  object,

and that the formatting process

replaces each format item with the text representation of the value of
  the corresponding object.

So when O'Reilly said

Output the result of multiplying the numbers together, but use
  replaceable parameter syntax of the Console object, and multiply the
  numbers within the call to the Console.WriteLine() method.

what they actually meant was

Output the result of multiplying the numbers together. Perform the
  calculation within a call to the Console.WriteLine() method, using an
  overload that formats the output according to a string parameter
  containing a placeholder for the result value.

Title: Replaceable parameter syntax meaning

Body:
You're quite right that it's not very clear, and the reason it's not very clear is that O'Reilly are taking liberties with their terminology. It's the kind of thing that only makes sense if you already know what they mean. And this is a course?

Probably the most commonly used overload of string.Format is the one that takes two parameters: a format string and an object array. You've probably used it to format a string with data from other variables:

int myNum = 123;
string message = string.Format("The number is {0}", myNum);

One of the Console.WriteLine() overloads takes these same two parameters, and for the same purpose:

Console.WriteLine("The number is {0}", myNum);

Microsoft tell us these markers in the string ({0}, {1} etc) are

indexed placeholders, called format items, that correspond to an
  object,

and that the formatting process

replaces each format item with the text representation of the value of
  the corresponding object.

So when O'Reilly said

Output the result of multiplying the numbers together, but use
  replaceable parameter syntax of the Console object, and multiply the
  numbers within the call to the Console.WriteLine() method.

what they actually meant was

Output the result of multiplying the numbers together. Perform the
  calculation within a call to the Console.WriteLine() method, using an
  overload that formats the output according to a string parameter
  containing a placeholder for the result value.


问:
Why does Linq to Entity Sum return null when the result set is empty?
There are quite a few questions on Stack Overflow about the Linq to Entity / Linq to SQL Sum extension method, about how it returns null when the result set is empty: 1, 2, 3, 4, 5, 6, 7, and many more, as well as a blog post discussing the issue here. I feel it is an inconsistency in the Linq implementation.

I am assuming at this point that it is not a bug, but is more or less working as designed. I understand that there are workarounds (for example, casting the field to a nullable type, so you can coalesce with ??), and I also understand that for the underlying SQL, a NULL result is expected for an empty result set.

But because the result of the Sum extension for non-nullable types is also non-nullable, why does the Linq to SQL / Linq to Entity Sum behave this way?

答:
The problem isn't that EF or LINQ2SQL return null for an empty set, it's that SQL returns null. Along those lines, what would you expect EF or LINQ2SQL to return when attempting to sum on a null value?

Generally, a null value is not a candidate for mathematical functions. Null usually means something along the lines of "unknown value" and is not the same as zero (the default value of an int or decimal in .NET). You can't perform math on it.

As such, it would be improper for the framework to decide to always substitute a default value for a null value and proceed to give you a misleadingly precise sum. Instead, the framework properly complains that the sum operation is impossible (because of the null value) and it is left to the caller to decide what to do in the case of a null value, using the techniques you have described and linked to in your question.


答:
Design as you talk

As already pointed out, you have some smelly stuff going on.

You say:

StructuredTune owns two Tune instances. It's own play plays the two Tunes one after the other according to a pattern (currently only A-B-A-B)

Your implementation however:

StructuredTune is a Tune that owns 2 tunes.

huh? Wow, euhmm. huh?

Now read the above again but change Tune with Melody.

huh?

Now read it another time, but now replace Tune with Progression

huh?

WTFsPM

Also known as WTFs / minute

And it starts with the big picture. A StructuredMelody knows about Melodies where as a SimpleMelody knows only about Notes.

This would be ok, because now a StructuredMelody could hold multiple StructuredMelodies that each have multiple StructuredMelodies. Cool!

Then we also have a StructuredTune that holds multiple Tunes that each hold a Structured Melody that holds multiple StructuredMelodies that ...

huh?

So a StructuredTune is actually a StructuredMelody. Only instead of having Melodies directly it holds Tunes that hold a Melody. wow! But then now you have the ability to also add Progressions (also known as Chords?).

Now read the same again, but with an extra iteration of those Progressions in them.

I'm lost

No really, I'm a musician and (should) know a lot about music stuff. But you lost me, a long while back.

The wrong pattern for the wrong reason

that is your problem :) You found a cool pattern and re using it everywhere. That's not cool!

Side note: been there done that. I abused the SingletonPattern for over a year, just because I liked it.

The better way

better because nothing is 'best'. We just have better solutions.

First of you should choose an approach. One could go for the pitch+note approach where a Note consists of a pitch and a duration. Or forget about pitch and only use a note and handle duration somewhere else.

You also should decide on how you are using chords. Is a chord a root Pitch with a chordQuality? or some Pitches crammed together. Or Notes?

A chord could have 3 Notes, each with a different duration. yuck :(

Then our progression. Is it some Playable stuff crammed together? Or do we in fact mean a chordProgression that as a rootChord and a progression (i.e. I-IV-V)? Or should we call it Harmony that has a rootTonality with a progression? lost again.

Depending on what you are building, different needs may arrive. You might also go for an approach where chords and progressions don't exist.

Just Notes that have a Pitch an a Duration.

A tune then is a collection of Notes and some kind of knowledge of when to start what note. We don't need chords here ;)

Or even simpler. We could define a Note with a pitch, start-time and stop-time. Stupid simple.

Your names are wrong

Names are important. They are the most important thing in your software. And defining them is as important.

Personally I would use the following approach:

The StartStoppables:

A Pitch

A Chord has multiple Pitch

Our StartStoppable interface:

```<code>interface StartStoppable
{
    public function start();
    public function stop();
}
</code>```

The Playables:

A Note has a Pitch and a Duration

A Harmony has Chord and a Duration

Our Playable interface:

```<code>interface Playable
{
    public function play();
}
</code>```

The progression related stuff:

A Progression defines a progression strategy (i.e. V-IV-I-I , other progression notations may be used)

A ChordProgression has multiple Harmony and is also Playable (!)

We then add some factories to aid us in the creation of our objects.

a PitchFactory can create a Pitch given a value and the used notation (i.e. Neo-Latin)

a ChordFactory can create a Chord from a given Pitch and chord quality.

a HarmonyFactory can create a Harmony from a given Pitch and HarmonySet (i.e. MajorTriad).

a HarmonyProgressionFactory can create a HarmonyProgression from a given Chord and a Progression

Our PitchFactory would look something like this:

```<code>class PitchFactory
{
    const ENGLISH = 0; //default notation
    const NEOLATINN = 1;

    public static function create(String $value, int $notation=0) {...}
}
</code>```

And then used as:

```<code>$pitch = PitchFactory::crate('DO', PitchFactory::NEOLATIN);
//or
$pitch = PitchFactory::create('C');;
</code>```

Our ChordFactory could be used as follows:

```<code>$chord = ChordFactory::create($pitch, ChordFactory::MAJOR); //Major chord
</code>```

As noted in other answers, these create methods could be moved into the objects themselves to create a nicer way of coding:

```<code>$pitch = Pitch::create('DO', PITCH::NEOLATIN);
$chord = Chord::create($pitch, Chord::MAJOR);
</code>```

We can then start using our notes and harmonies:

```<code>$length = 1; //whatever this means

$note = new Note($pitch, $length);

$harmony = new Harmony($chord, $length);

//or maybe a minor triad with root set to $pitch
$harmony = Harmony::create($pitch, $length, Harmony::MinorTriad);
</code>```

And then finally our HarmonyProgression:

```<code>$progression = new Progression('V-IV-I-I');
$harmonyProgression = HarmonyProgressionFactory::create($chord, $progression);
</code>```

Later on the notations could be factored into an own class. This will give you flexibility in being able to use Tabular, Roman, etc. notations independent of the rest of your application.

Title: Requesting feedback on my OO design

Body:
Design as you talk

As already pointed out, you have some smelly stuff going on.

You say:

StructuredTune owns two Tune instances. It's own play plays the two Tunes one after the other according to a pattern (currently only A-B-A-B)

Your implementation however:

StructuredTune is a Tune that owns 2 tunes.

huh? Wow, euhmm. huh?

Now read the above again but change Tune with Melody.

huh?

Now read it another time, but now replace Tune with Progression

huh?

WTFsPM

Also known as WTFs / minute

And it starts with the big picture. A StructuredMelody knows about Melodies where as a SimpleMelody knows only about Notes.

This would be ok, because now a StructuredMelody could hold multiple StructuredMelodies that each have multiple StructuredMelodies. Cool!

Then we also have a StructuredTune that holds multiple Tunes that each hold a Structured Melody that holds multiple StructuredMelodies that ...

huh?

So a StructuredTune is actually a StructuredMelody. Only instead of having Melodies directly it holds Tunes that hold a Melody. wow! But then now you have the ability to also add Progressions (also known as Chords?).

Now read the same again, but with an extra iteration of those Progressions in them.

I'm lost

No really, I'm a musician and (should) know a lot about music stuff. But you lost me, a long while back.

The wrong pattern for the wrong reason

that is your problem :) You found a cool pattern and re using it everywhere. That's not cool!

Side note: been there done that. I abused the SingletonPattern for over a year, just because I liked it.

The better way

better because nothing is 'best'. We just have better solutions.

First of you should choose an approach. One could go for the pitch+note approach where a Note consists of a pitch and a duration. Or forget about pitch and only use a note and handle duration somewhere else.

You also should decide on how you are using chords. Is a chord a root Pitch with a chordQuality? or some Pitches crammed together. Or Notes?

A chord could have 3 Notes, each with a different duration. yuck :(

Then our progression. Is it some Playable stuff crammed together? Or do we in fact mean a chordProgression that as a rootChord and a progression (i.e. I-IV-V)? Or should we call it Harmony that has a rootTonality with a progression? lost again.

Depending on what you are building, different needs may arrive. You might also go for an approach where chords and progressions don't exist.

Just Notes that have a Pitch an a Duration.

A tune then is a collection of Notes and some kind of knowledge of when to start what note. We don't need chords here ;)

Or even simpler. We could define a Note with a pitch, start-time and stop-time. Stupid simple.

Your names are wrong

Names are important. They are the most important thing in your software. And defining them is as important.

Personally I would use the following approach:

The StartStoppables:

A Pitch

A Chord has multiple Pitch

Our StartStoppable interface:

interface StartStoppable
{
    public function start();
    public function stop();
}

The Playables:

A Note has a Pitch and a Duration

A Harmony has Chord and a Duration

Our Playable interface:

interface Playable
{
    public function play();
}

The progression related stuff:

A Progression defines a progression strategy (i.e. V-IV-I-I , other progression notations may be used)

A ChordProgression has multiple Harmony and is also Playable (!)

We then add some factories to aid us in the creation of our objects.

a PitchFactory can create a Pitch given a value and the used notation (i.e. Neo-Latin)

a ChordFactory can create a Chord from a given Pitch and chord quality.

a HarmonyFactory can create a Harmony from a given Pitch and HarmonySet (i.e. MajorTriad).

a HarmonyProgressionFactory can create a HarmonyProgression from a given Chord and a Progression

Our PitchFactory would look something like this:

class PitchFactory
{
    const ENGLISH = 0; //default notation
    const NEOLATINN = 1;

    public static function create(String $value, int $notation=0) {...}
}

And then used as:

$pitch = PitchFactory::crate('DO', PitchFactory::NEOLATIN);
//or
$pitch = PitchFactory::create('C');;

Our ChordFactory could be used as follows:

$chord = ChordFactory::create($pitch, ChordFactory::MAJOR); //Major chord

As noted in other answers, these create methods could be moved into the objects themselves to create a nicer way of coding:

$pitch = Pitch::create('DO', PITCH::NEOLATIN);
$chord = Chord::create($pitch, Chord::MAJOR);

We can then start using our notes and harmonies:

$length = 1; //whatever this means

$note = new Note($pitch, $length);

$harmony = new Harmony($chord, $length);

//or maybe a minor triad with root set to $pitch
$harmony = Harmony::create($pitch, $length, Harmony::MinorTriad);

And then finally our HarmonyProgression:

$progression = new Progression('V-IV-I-I');
$harmonyProgression = HarmonyProgressionFactory::create($chord, $progression);

Later on the notations could be factored into an own class. This will give you flexibility in being able to use Tabular, Roman, etc. notations independent of the rest of your application.


问:
Decoupling software components via naming convention
I'm currently evaluating alternatives to refactor a drivermanagement.

In my multitier architecture I have

Baseclass

DAL.Device //my entity

Interfaces

BL.IDriver //handles the dataprocessing between application and device

BL.IDriverCreator //creates an IDriver from a Device

BL.IDriverFactory //handles the driver creation requests

Every specialization of Device has a corresponding IDriver implementation and a corresponding IDriverCreator implementation.

At the moment the mapping is fix via a type check within the business layer / DriverFactory. That means every new driver needs a) changing code within the DriverFactory and b) referencing the new IDriver implementation / assembly. On a customers point of view that means, every new driver, used or not, needs a complex revalidation of their hardware environment, because it's a critical process.

My first inspiration was to use a caliburn micro like nameconvention

see Caliburn.Micro: Xaml Made Easy

BL.RestDriver

BL.RestDriverCreator

DAL.RestDevice

After receiving the RestDevicewithin the IDriverFactory I can load all driver dlls via reflection and do a namesplitting/comparing (extracting the xx from xxDriverCreator and xxDevice)

Another idea would be a custom attribute (which also leads to comparing strings).

My question: is that a good approach above layer borders? If not, what would be a good approach?

答: Relying on naming convention for creating plugin mechanism is a well known approach to avoid unnecessary boiler plate code and to follow the Open/Closed principle. However, the convention should be documented well, and you should take some precautions against typos - for example, if someone writes "Devices" or "Devce", make sure your driver manager will become aware of that and signal an error.</p>


问:
Is there any practical use for the empty type in Common Lisp?
The Common Lisp spec states that nil is the name of the empty type, but I've never found any situation in Common Lisp where I felt like the empty type was useful/necessary. Is it there just for completeness sake (and removing it wouldn't cause any harm to anyone)? Or is there really some practical use for the empty type in Common Lisp? If yes, then I would prefer an answer with code example.

For example, in Haskell the empty type can be used when binding foreign data structures, to make sure that no one tries to create values of that type without using the data structure's foreign interface (although in this case, the type is not really empty).

答:
One practical use is to generate errors when the implementation takes your declarations into account.  It might be specially useful in machine-generated and/or debug code, or when you want to turn e.g. a dynamic variable obsolete and at some point declare it of type nil, so reading from, writing to or binding it will signal an error (or is otherwise undefined behavior), but checking for boundp will not.

Another use is if you can only pass a type specifier to e.g. a filtering API, so nil (no value is of type nil, nil is a subtype of any type) can be as useful as t (any value is of type t, t is a supertype of any type), but the other way around.

EDIT: It also serves as a base type specifier, as the types (or) and (member) are equivalent to the type nil.


答:
In general, there's nothing wrong with passing functions to other functions. If you're making asynchronous calls and want to do something with the result, then you'd need some sort of callback mechanism.

There are a few potential drawbacks of simple callbacks though:

Making a series of calls can require deep nesting of callbacks.

Error handling can need repetition for each call in a sequence of calls.

Coordinating multiple calls is awkward, like making
multiple calls at the same time and then doing something once they
are all finished.

There's no general way of cancelling a set of calls.

With simple webservices the way you're doing it works fine, but it becomes awkward if you need more complex sequencing of calls. There are some alternatives though. With JavaScript for example, there's been a shift towards the use of promises (What's so great about javascript promises).

They still involve passing functions to other functions but asynchronous calls return a value that takes a callback rather than take a callback directly themselves. This gives more flexibility for composing these calls together. Something like this can be implemented fairly easily in ActionScript.

Title: Passing functions into other functions as parameters, bad practice?

Body:
We've been in the process of changing how our AS3 application talks to our back end and we're in the process of implementing a REST system to replace our old one.

Sadly the developer who started the work is now on long term sick leave and it's been handed over to me. I've been working with it for the past week or so now and I understand the system, but there's one thing that's been worrying me. There seems to be a lot of passing of functions into functions. For example our class that makes the call to our servers takes in a function that it will then call and pass an object to when the process is complete and errors have been handled etc.

It's giving me that "bad feeling" where I feel like it's horrible practice and I can think of some reasons why but I want some confirmation before I propose a re-work to system. I was wondering if anyone had any experience with this possible problem?


问:
When is type testing OK?
Assuming a language with some inherent type safety (e.g., not JavaScript):

Given a method that accepts a SuperType, we know that in most cases wherein we might be tempted to perform type testing to pick an action:

```<code>public void DoSomethingTo(SuperType o) {
  if (o isa SubTypeA) {
    o.doSomethingA()
  } else {
    o.doSomethingB();
  }
}
</code>```

We should usually, if not always, create a single, overridable method on the SuperType and do this:

```<code>public void DoSomethingTo(SuperType o) {
  o.doSomething();
}
</code>```

... wherein each subtype is given its own doSomething() implementation. The rest of our application can then be appropriately ignorant of whether any given SuperType is really a SubTypeA or a SubTypeB.

Wonderful.

But, we're still given is a-like operations in most, if not all, type-safe languages. And that suggests a potential need for explicit type testing.

So, in what situations, if any, should we or must we perform explicit type testing?

Forgive my absent mindedness or lack of creativity. I know I've done it before; but, it was honestly so long ago I can't remember if what I did was good! And in recent memory, I don't think I've encountered a need to test types outside my cowboy JavaScript.

答:
It's acceptable in a case where you have to make a decision that involves two types and this decision is encapsulated in an object outside of that type hierarchy.  For instance, let's say you're scheduling which object gets processed next in a list of objects waiting for processing:

```<code>abstract class Vehicle
{
    abstract void Process();
}

class Car : Vehicle { ... }
class Boat : Vehicle { ... }
class Truck : Vehicle { ... }
</code>```

Now let's say our business logic is literally "all cars get precedence over boats and trucks".  Adding a Priority property to the class doesn't allow you to express this business logic cleanly because you'll end up with this:

```<code>abstract class Vehicle
{
    abstract void Process();
    abstract int Priority { get }
}

class Car : Vehicle { public Priority { get { return 1; } } ... }
class Boat : Vehicle { public Priority { get { return 2; } } ... }
class Truck : Vehicle { public Priority { get { return 2; } } ... }
</code>```

The problem is that now to understand the priority ordering you have to look at all the subclasses, or in other words you've added coupling to the subclasses.

You should of course make the priorities into constants and put them into a class by themselves, which helps keep scheduling business logic together:

```<code>static class Priorities
{
    public const int CAR_PRIORITY = 1;
    public const int BOAT_PRIORITY = 2;
    public const int TRUCK_PRIORITY = 2;
}
</code>```

However, in reality the scheduling algorithm is something that might change in the future and it might eventually depend on more than just type.  For instance, it might say "trucks over a weight of 5000 kg get special priority over all other vehicles."  That's why the scheduling algorithm belongs in its own class, and it's a good idea to inspect the type to determine which one should go first:

```<code>class VehicleScheduler : IScheduleVehicles
{
    public Vehicle WhichVehicleGoesFirst(Vehicle vehicle1, Vehicle vehicle2)
    {
        if(vehicle1 is Car) return vehicle1;
        if(vehicle2 is Car) return vehicle2;
        return vehicle1;
    }
}
</code>```

This is the most straightforward way to implement the business logic and still the most flexible to future changes.

Title: When is type testing OK?

Body:
It's acceptable in a case where you have to make a decision that involves two types and this decision is encapsulated in an object outside of that type hierarchy.  For instance, let's say you're scheduling which object gets processed next in a list of objects waiting for processing:

abstract class Vehicle
{
    abstract void Process();
}

class Car : Vehicle { ... }
class Boat : Vehicle { ... }
class Truck : Vehicle { ... }

Now let's say our business logic is literally "all cars get precedence over boats and trucks".  Adding a Priority property to the class doesn't allow you to express this business logic cleanly because you'll end up with this:

abstract class Vehicle
{
    abstract void Process();
    abstract int Priority { get }
}

class Car : Vehicle { public Priority { get { return 1; } } ... }
class Boat : Vehicle { public Priority { get { return 2; } } ... }
class Truck : Vehicle { public Priority { get { return 2; } } ... }

The problem is that now to understand the priority ordering you have to look at all the subclasses, or in other words you've added coupling to the subclasses.

You should of course make the priorities into constants and put them into a class by themselves, which helps keep scheduling business logic together:

static class Priorities
{
    public const int CAR_PRIORITY = 1;
    public const int BOAT_PRIORITY = 2;
    public const int TRUCK_PRIORITY = 2;
}

However, in reality the scheduling algorithm is something that might change in the future and it might eventually depend on more than just type.  For instance, it might say "trucks over a weight of 5000 kg get special priority over all other vehicles."  That's why the scheduling algorithm belongs in its own class, and it's a good idea to inspect the type to determine which one should go first:

class VehicleScheduler : IScheduleVehicles
{
    public Vehicle WhichVehicleGoesFirst(Vehicle vehicle1, Vehicle vehicle2)
    {
        if(vehicle1 is Car) return vehicle1;
        if(vehicle2 is Car) return vehicle2;
        return vehicle1;
    }
}

This is the most straightforward way to implement the business logic and still the most flexible to future changes.


答:
There is also something to be said for where in your schedule are you at this point.  For example, on a Friday afternoon I may pick quite a different option than I would on a Tuesday or Wednesday where I know I'm coming back the next day to pick it up.  At the same time, starting on something can carry some initial tasks, e.g. updating the bug tracking software or creating a branch in source control, that can be good to get out of the way earlier rather than later.

There are likely to be some administrative things,e.g. time sheets, reflections on what got done and didn't get done, that may be worth spending that half-hour that may end up taking a bit more time than you think if you enjoy things like reflecting on how your week has gone.  "Life moves pretty fast. If you don't stop and look around once in a while, you could miss it." as Ferris Bueller said some 24 years ago now is something else to point out here.

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

Body:
Inspired by this question:
What to do about "stopping point syndrome"?

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

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


问:
How to avoid being forked into oblivion by a more powerful contributor?
As recently reported here:

Xamarin has forked Cocos2D-XNA, a 2D/3D game development framework,
  creating a cross-platform library that can be included in PCL
  projects.

However the founder of the project that was forked says:

The purpose of the MIT license is to unencumber your fair use. Not to
  encourage you to take software, rebrand it as your own, and then "take
  it in a new direction" as you say.

While not illegal, it is unethical.

It seems that the GitHub page of the new project doesn't even indicate that it's a fork in a typical GitHub manner, opting for an easily-removable History section instead (see bottom).

So my questions are:

Was Xamarin's action and the way the action was done ethical or not?

Is it possible to avoid such a situation if you are a single
developer or a small unfunded group of developers?

I am hoping this could be either a wiki question or there will be some objective answers grounded on modern OSS ethics/philosophy.

答:
Releasing a project under the MIT license is giving people permission to fork the project. Part of the philosophy behind free software is to give users and developers the right to use, modify, and release the software in ways that wouldn't normally be allowed. If you don't want people to do this, then don't use the MIT license. You can't really complain when people use code under the terms of the license that you've given them.

Forks are a fairly normal thing to happen in the free software community. It looks like the fork's developers tried to contribute to the original project, and didn't agree so they contributed to their own project instead. Free software encourages this so that developers are not prevented from modifying software because the owners don't like their changes.

Also, by releasing something under a free software license, you're benefiting from other people's contributions, contributions you might not have received if it was under a different license. If you accept contributions under a license, you should respect the terms of the license yourself.

One way to maintain control over an official version is to rely on things like trademarks. Mozilla Corporation for example has a trademark on Firefox which allows them to dictate what people can do with Firefox even though it's open source (See Iceweasel for the fork of this).

Other licenses like LGPL still allow forks, but keep the code open. This way, you can at least incorporate any changes from the fork into your original project, and benefit from the development on the fork. LGPL code can use any MIT licensed code so if you wanted more control over the project, you could use LGPL instead.


答:
Sometimes you do not want to add a common method to all the classes because it really is not their responsibility to perform that specific task.

For example you want to draw some entities but do not want to add the drawing code directly to them (which makes sense). In languages not supporting multiple dispatch you might end up with the following code:

```<code>void DrawEntity(Entity entity) {
    if (entity instanceof Circle) {
        DrawCircle((Circle) entity));
    else if (entity instanceof Rectangle) {
        DrawRectangle((Rectangle) entity));
    } ...
}
</code>```

This becomes problematic when this code appears at several places and you need to modify it everywhere when adding new Entity type. If that is the case then it can be avoided by using the Visitor pattern but sometimes it is better to just keep things simple and not overengineer it. Those are the situations when type testing is OK.

Title: When is type testing OK?

Body:
Assuming a language with some inherent type safety (e.g., not JavaScript):

Given a method that accepts a SuperType, we know that in most cases wherein we might be tempted to perform type testing to pick an action:

```<code>public void DoSomethingTo(SuperType o) {
  if (o isa SubTypeA) {
    o.doSomethingA()
  } else {
    o.doSomethingB();
  }
}
</code>```

We should usually, if not always, create a single, overridable method on the SuperType and do this:

```<code>public void DoSomethingTo(SuperType o) {
  o.doSomething();
}
</code>```

... wherein each subtype is given its own doSomething() implementation. The rest of our application can then be appropriately ignorant of whether any given SuperType is really a SubTypeA or a SubTypeB.

Wonderful.

But, we're still given is a-like operations in most, if not all, type-safe languages. And that suggests a potential need for explicit type testing.

So, in what situations, if any, should we or must we perform explicit type testing?

Forgive my absent mindedness or lack of creativity. I know I've done it before; but, it was honestly so long ago I can't remember if what I did was good! And in recent memory, I don't think I've encountered a need to test types outside my cowboy JavaScript.

Body:
Sometimes you do not want to add a common method to all the classes because it really is not their responsibility to perform that specific task.

For example you want to draw some entities but do not want to add the drawing code directly to them (which makes sense). In languages not supporting multiple dispatch you might end up with the following code:

void DrawEntity(Entity entity) {
    if (entity instanceof Circle) {
        DrawCircle((Circle) entity));
    else if (entity instanceof Rectangle) {
        DrawRectangle((Rectangle) entity));
    } ...
}

This becomes problematic when this code appears at several places and you need to modify it everywhere when adding new Entity type. If that is the case then it can be avoided by using the Visitor pattern but sometimes it is better to just keep things simple and not overengineer it. Those are the situations when type testing is OK.


答:
Was Xamarin's action and the way the action was done ethical or not?

Well, let's ask an expert - The Open Source Initiative's listing of the MIT License itself, with the license quoted in its entirety:

The MIT License (MIT)

Copyright (c)

Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

If anyone - individual or company - releases software/source code with an MIT license, it means that anyone else - individual or company can "deal in the Software without restriction". So long as the copyright notice stays intact, they are pretty much able to do as they please.

This is one of those cases when ethics and legality are pretty much exactly the same. If a person or group didn't understand the license or its implications then they failed to do their due diligence. The Open Source Initiative provides lots of other nice resources to help us understand licenses like the MIT variant. Let's look at a few clauses of their Open Source Definition:

1) Free Redistribution - The license shall not restrict any party from selling or giving away the software as a component of an aggregate
  software distribution containing programs from several different
  sources. The license shall not require a royalty or other fee for such
  sale.

3) Derived Works - The license must allow modifications and derived works, and must allow them to be distributed under the same terms as
  the license of the original software.

5) No Discrimination Against Persons or Groups - The license must not discriminate against any person or group of persons.

6) No Discrimination Against Fields of Endeavor - The license must not restrict anyone from making use of the program in a specific field of
  endeavor. For example, it may not restrict the program from being used
  in a business, or from being used for genetic research.

To my reading this seems all abundantly clear: releasing something as open source, especially with the MIT license, allows someone to freely take the software, change it, package it, and sell it to pretty much whoever they like, so long as they don't remove your copyright notice and claim it to be their own sole work.

As the author you are explicitly giving up the right to be picky and choosy. You don't get to decide who or what can benefit from your software or make use of it, and you don't get to decide why they are using it. You explicitly give up that right.

The idea is that you are contributing to the greater good by explicitly renouncing any legal rights you have to control and restrict use and change of what you have made. If Microsoft wants to fork your FluffBall project and sell it for $2k per seat as WindowsSpongeCake, they can. Wasn't letting people do whatever they want the whole point of your project in the first place?

Is it possible to avoid such a situation if you are a single developer or a small unfunded group of developers?

Kind of! First, use a license that's appropriate to you and your organization's goals and desires. If you don't want anyone to use it in a way you don't approve of, you probably shouldn't be releasing it as Open Source - and frankly you maybe shouldn't be releasing it at all! If you don't want anyone to use a derivative work (like a fork) on a commercial project you should probably go for a copyleft version of the GPL. If you want a noncommercial license you should probably get a copyright/license lawyer to advise, because this is often not considered "open source" software at all and there isn't any major pre-written license to support this case.

The issue with the Xamarin and Coco kerfuffle is not a matter of ethics or legality - it's about an internet fight between a few people who have a beef with each other. We're all human, it happens. It seems to be the result of being unable to collaborate/cooperate, likely due to a personality conflict or incompatible visions for how the project should be handled.

So the other way of defense is being open to collaboration and change, but understand that if it doesn't work out and visions diverge...well, that's the reason for the option to fork and have your own separate project.

It's very human and understandable for feelings of ownership and popularity to make software projects very, very complicated. But the goal of open source is to try to transcend that and allow the best software to be available freely to all.

Bottom-line, be clear about your goals when you are deciding a license, and understand its implications for your future control and direction of the project. If you just want to donate to the greater good, open source is the way to go. If you want to control your project more tightly and have ownership and at least a legal case if someone tries to market your project or absorb it into their own (in part or entirely), you'll need a different license and will probably need to sort it out with a lawyer.

Title: How to avoid being forked into oblivion by a more powerful contributor?

Body:
As recently reported here:

Xamarin has forked Cocos2D-XNA, a 2D/3D game development framework,
  creating a cross-platform library that can be included in PCL
  projects.

However the founder of the project that was forked says:

The purpose of the MIT license is to unencumber your fair use. Not to
  encourage you to take software, rebrand it as your own, and then "take
  it in a new direction" as you say.

While not illegal, it is unethical.

It seems that the GitHub page of the new project doesn't even indicate that it's a fork in a typical GitHub manner, opting for an easily-removable History section instead (see bottom).

So my questions are:

Was Xamarin's action and the way the action was done ethical or not?

Is it possible to avoid such a situation if you are a single
developer or a small unfunded group of developers?

I am hoping this could be either a wiki question or there will be some objective answers grounded on modern OSS ethics/philosophy.

ContentLicense: CC BY-SA 4.0


问:
Why is cleverness considered harmful in programming by some people?
I've noticed a lot of questions lately relating to different abstraction techniques, and answers saying basically that the techniques in question are "too clever." I would think that part of our jobs as programmers is to determine the best solutions to the problems we are given to solve, and cleverness is helpful in doing that.

So my question is: are the people who think certain abstraction techniques are too clever opposed to cleverness per se, or is there some other reason for the objection?

EDIT: This parser combinator is an example of what I would consider to be clever code. I downloaded this and looked it over for about half an hour. Then I stepped through the macro expansion on paper and saw the light. Now that I understand it, it seems much more elegant than the Haskell parser combinator.

答:
In my opinion, cleverness per se isn't a problem. Usually we can make confusions about "clever" (without sarcasm) and "insightfull" code. What I see as a problem, is the fact that usually the "clever" (with sarcasm) code contains implicit not-visible requirements, making it harder to debug and maintain along time.

There are several known algorithms that are clever. Quicksort is one, IMO.

"Clever" (with sarcasm) code usually make assumptions about variables being set and states of the system that are virtually disconnected from the "clever" code (as files opened previously, network connections, databases, etc...).

The amount of data you have to load on your brain to maintain correctly a "clever" code is usually to big to have a good cost-benefit ratio.


答:
I wouldn't call it unethical.  I would call it unsportsmanlike.  There's an unwritten expectation that you will give a good faith effort to improve the original version before deciding to fork, and it seems the original author feels that good faith effort wasn't made.

That being said, the best way to avoid your software being forked is to be responsive to customer requests in such a way that your software has as broad an appeal as possible.  No one is going to give support to a fork if they know the original is superior.  Aside from that, your only protection is to change the licensing terms.


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

It states:

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

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

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

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

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

答:
I'm not a lawyer, but my understanding is that a modification would be anything that's considered a derivative work under copyright law. This is a grey area where borderline cases may need to be decided in court, so it may be better to be safe and do what the license says anyway. Also, consider asking the original developers, they often clarify ambiguous parts of the license to users.

This issue came up when implementing GNU after some programmers had read the source code of Unix (See Reading non-free code). This is for non-free code but the same idea applies. Based on these guidelines:

Item (1) could count as a modification. Although it could depend on how different your implementation is.

Item (2) wouldn't be a modification if you implement it in a different way.

Item (3) would be a modification, because it leaves some of the code of the original in the new version, or at least some of the structure.

The safest way to reimplement something without violating copyright is to use something like clean room design. This provides a defence in case you are sued for infringement.


问:
Best approach for tracking dependent state
Let's pretend I work on a project tracking application.  The application is a database backed, server hosted, web application.  In this application there are Projects which have many Activities which have many Tasks.  A Task has two date fields an originalDueDate and a projectedDueDate.

In addition, there are dynamic fields on the Activities and the Projects which indicate whether the Activity or Project is behind schedule based on the projected due dates of the child tasks and various other variables such as remaining buffer time, etc.

There are a number of things that can cause the projectedDueDate to change.  For example, an employee working on the project may (via a server request) enter in a shipping delay.  Alternatively, a site may (via a server request) enter in an unexpected closure.

When any of these things occur I need to not only update the projectedDueDate of the Task but also trigger the corresponding Project and Activity to update as well.

What is the best way to do this?

I've thought of the observer pattern but I don't keep a single copy of all these objects in memory.  When a request comes in, I query the Task in from the database, at that point there is no associated Activity in memory that would be a listener.  I could remove the ability to query for Tasks and force the application to query first by Project, then by Activity (in context of Project), then by task (in context of Activity) adding the observer relationships at each step but I'm not sure if that is the best way.

I could setup a database event listening system so when a Task modified event is dispatched I have a handler which queries for the Activity at that point.

I could simply setup a two-way relationship between Task and Activity so that the Task knows about the parent Activity and when the Task updates his state the Task grabs his parent and updates state.

Right now I'm stuck considering all the options and am wondering if any single approach (doesn't have to be a listed approach) is jumping out at others as the best approach.

答:
As already said, I don’t think the Observer pattern applies, because your Projects, Activities and Tasks are not objects.  You cannot register an individual Project record to receive notifications from Task record updates.  The Observer patterns could be used only with objects in memory.

You could put a trigger on the Tasks table to runs a stored procedure that updates the relevant Activity or Project.  This can work but you have to implement part of your business logic in SQL.  It would probably duplicate code in your server.  Also, when you update multiple Tasks, you would trigger that procedure as many times as you have tasks.  It is not necessarily performant.

You have to think the dependency is not necessarily from Task to Activity,  You might want to move an Activity with all its Tasks in bulk.

What I would suggest is to wrap all your schedule updates in module I’ll call the “Scheduler”.  The Sheduler would provide a number of services for adding or updating your Tasks, or Activities or Projects.  All updates would go thru that Scheduler.  Whenever a request is made, the Scheduler would open a transaction on your database, execute the requested updates and adjust any other dependent data acordingly before committing.

It might look a bit inelegant, the updates are not automatic, and need to be written out, but I am pretty sure the code would be easier to understand and to debug.


问:
Progressive Enhancement vs. Single Page Apps
I just got back from a conference in Boston called An Event Apart.

A really popular theme amongst the speakers was the idea of progressive enhancement - a site's content should go in the HTML, and JavaScript should only be used to enhance behavior.

The arguments that the speakers gave for progressive enhancement were very compelling. Not only is it a solid pattern for supporting older browsers, and devices on a network with low bandwidth, but HTML fails much more gracefully than JavaScript (i.e. markup that is not supported is just ignored, while if a browser throws an exception while executing your script - you are hosed).

Jeremy Keith gave a particularly insightful talk about this.

But what about single page web apps like Backbone and Angular? The whole design behind these frameworks seems to push the developer toward moving content out of the HTML, and into something like a JSON API.

I can not seem to gel these two design patterns: progressive enhancement vs. single page web apps. Are there instances when one is better than the other? Or are they not even antagonistic technologies, and I am missing something here with my mental model?

答:
I'm of the view that the reduced page load is probably quite a good for servers, and the network.   I'd love to see more SPAs used correctly.

I'm off the view though that this requires two things:

1) setting up all of your links as standard request/response links on initial load, let your SPA framework/library then replace these with an updated (interactive) version once the browser loads and the JS engine identifies that SPA support is available.  This truly is progresive enhancement; the JS is loaded on top of the existing html website, and this is better for search engines, assistive technologies, and older browsers.

and

2) The server needs to be responsive to routes like /foo/bar/json and foo/bar  by serving the correct format;   realistically if you're wrapping everything in layouts and partials to get the first page, you should be able to get everything via layouts and partials for the 2nd and subsequent pages as well.

There's a fair bit of work here; admittedly, but if you've got control over the full stack it does balance the two technologies.


问:
Is it good practice to use NoStackTrace in scala?
I came across the NoStackTrace mixin for Exceptions in scala.

Is it good practice to use it, or should it be considered "internal" to scala and left alone?

答:
For a moment, lets head over to Stack Overflow - How slow are Java exceptions?

It turns out that the expensive part of throwing exceptions is the population of the stack trace that goes along with the exception.

This stack trace is very helpful when debugging problems to try to figure out where things are getting called from.  One of the standard questions asked of problems is "what is the code" and "what is the stack trace".  Without those two things, diagnosing a problem is nigh-impossible.

However, not all exceptions are generated by problems.  Some of them, you almost expect.

Consider the situation that you've got a String from some source and you want to get it back into an integer format with Integer.decode.

Integer foo = Integer.decode(str);
```

<p>But that <code>decode</code> throws a checked <code>NumberFormatException</code>.  Ok...</p>

<pre class="lang-java prettyprint-override"><code>Integer foo;
try {
    foo = Integer.decode(str);
} catch (NumberFromatException e) {
    // raise an error back to the input form
}
</code>```

But you really don't care about the stack trace there... but its there.  And just a tad bit slower because it populated the stack trace.

Thus, in Scala, you've got the NoStackTrace:

A trait for exceptions which, for efficiency reasons, do not fill in the stack trace. Stack trace suppression can be disabled on a global basis via a system property wrapper in scala.sys.SystemProperties.

Don't populate what you don't need.  You don't care about the stack trace because you are handling it right there and then.  This isn't something that is getting passed up, and its not all that exceptional either.

Its not bad practice to use it when you know what you're handling.  But, if you're passing this on up the chain - don't use it - you might just need to log where some exception came from.

Body:
For a moment, lets head over to Stack Overflow - How slow are Java exceptions?

It turns out that the expensive part of throwing exceptions is the population of the stack trace that goes along with the exception.

This stack trace is very helpful when debugging problems to try to figure out where things are getting called from.  One of the standard questions asked of problems is "what is the code" and "what is the stack trace".  Without those two things, diagnosing a problem is nigh-impossible.

However, not all exceptions are generated by problems.  Some of them, you almost expect.

Consider the situation that you've got a String from some source and you want to get it back into an integer format with Integer.decode.

Integer foo = Integer.decode(str);

But that decode throws a checked NumberFormatException.  Ok...

Integer foo;
try {
    foo = Integer.decode(str);
} catch (NumberFromatException e) {
    // raise an error back to the input form
}

But you really don't care about the stack trace there... but its there.  And just a tad bit slower because it populated the stack trace.

Thus, in Scala, you've got the NoStackTrace:

A trait for exceptions which, for efficiency reasons, do not fill in the stack trace. Stack trace suppression can be disabled on a global basis via a system property wrapper in scala.sys.SystemProperties.

Don't populate what you don't need.  You don't care about the stack trace because you are handling it right there and then.  This isn't something that is getting passed up, and its not all that exceptional either.

Its not bad practice to use it when you know what you're handling.  But, if you're passing this on up the chain - don't use it - you might just need to log where some exception came from.


答:
It would be shady to allow people to draw incorrect conclusions about the authorship of whatever code the fork ships, even if the legalities are covered by providing the necessary notices and revision history for anyone who chooses to look closely. So maybe Xamarin's presentation is unethical, maybe it isn't, but I think that's the basis on which to judge it: does it mislead?

The license lays down permission to use the code and a requirement to include relevant copyright notices with copies of the code. That's all at quite a low level. It doesn't discuss how you should publicly summarize who contributed what, but just because that's outside the scope of the license and not part of the legal agreement doesn't mean anything goes ethically. Ethics vary, but giving honest credit where due is quite a widely-held principle so it's easy to see why failing to do so will give offence.

Like everyone says there's no intention in the MIT license to prevent forks, so that's not unethical of itself. If "rebrand it as your own" is code for "make public claims of credit you don't deserve", then sure that would be unethical if true.

As for preventing it happening to you: if you want to avoid the situation of someone else insinuating that your code is theirs, then you need a loud voice when claiming credit. If you want to avoid the situation of someone creating a fork of your code that might eventually prove more popular than your original (either due to their greater resources or just their focussing on the "right" user needs) then I think you're out of luck in OSS. You can't just decide to be right if another group wants different features in the software from what you want, and if (in the view of users) you're wrong then you should lose regardless of being there first. This is a consequence of the primary open source principle (or properly, free software principle) that the author doesn't control the software, the people who run it do.


问:
How to cleanly add after-the-fact commits from the same feature into git tree
I am one of two developers on a system.  I make most of the commits at this time period.  My current git workflow is as such:

there is master branch only (no develop/release)

I make a new branch when I want to do a feature, do lots of commits, and then when I'm done, I merge that branch back into master, and usually push it to remote.

...except, I am usually not done.  I often come back to alter one thing or another and every time I think it is done, but it can be 3-4 commits before I am really done and move onto something else.

Problem

The problem I have now is that .. my feature branch tree is merged and pushed into master and remote master, and then I realize that I am not really done with that feature, as in I have finishing touches I want to add, where finishing touches may be cosmetic only, or may be significant, but they still belong to that one feature I just worked on.

What I do now

Currently, when I have extra after-the-fact commits like this, I solve this problem by rolling back my merge, and re-merging my feature branch into master with my new commits, and I do that so that git tree looks clean.  One clean feature branch branched out of master and merged back into it.  I then push --force my changes to origin, since my origin doesn't see much traffic at the moment, so I can almost count that things will be safe, or I can even talk to other dev if I have to coordinate.  But I know it is not a good way to do this in general, as it rewrites what others may have already pulled, causing potential issues.  And it did happen even with my dev, where git had to do an extra weird merge when our trees diverged.

Other ways to solve this which I deem to be not so great

Next best way is to just make those extra commits to the master branch directly, be it fast-forward merge, or not.  It doesn't make the tree look as pretty as in my current way I'm solving this, but then it's not rewriting history.

Yet another way is to wait.  Maybe wait 24 hours and not push things to origin.  That way I can rewrite things as I see fit.  The con of this approach is time wasted waiting, when people may be waiting for a fix now.

Yet another way is to make a "new" feature branch every time I realize I need to fix something extra.  I may end up with things like feature-branch feature-branch-html-fix, feature-branch-checkbox-fix, and so on, kind of polluting the git tree somewhat.

Is there a way to manage what I am trying to do without the drawbacks I described?  I'm going for clean-looking history here, but maybe I need to drop this goal, if technically it is not a possibility.

Sample After-the-Fact Commit Messages

```<code>Main commits:  alter module behavior to give user more information
</code>```

Here I thought I was done, check out,  & merge to master, then oops, forgot this (OFT):

```<code>OFT:  (enhancement) added better error messages
</code>```

Okay, now I am done!

Later, user comes back and asks for an enhancement/feature.  Turns out a certain input number for an order can have a revision associated with it.  So it's really two numbers, not one.

```<code>OFT:  (feature-add):  fix up order input to accept revisions
</code>```

Now I'm done ...

```<code>OFT:  (bug-fix) there was a bug with the two-number input method, fix SQL for that
</code>```

okay now I'm done ...

```<code>OFT:  (enhancement) oh wait, improved error messages again, for clarity!
</code>```

答:
When you merge into master, you are essentially declaring "I'm done".  It's like dropping your mail at the post office, or signing a lease.  You can't change your mind after merging (of course, in reality you can, thanks to the wonders of technology; it's just bad etiquette when collaborating with others).

If you feel that you need to add more to it, then what you're adding is either:

A non-essential improvement, which means you can treat it as a new branch and work from there.

Or an important bug fix, which should happen very rarely – this is why one should always run the tests before merging into master.  In this case, be sure to let everyone know that master is broken and resolve the situation quickly.

If you feel that your feature still needs more revising, then don't merge into master!

If for some reason other developers want a sneak peek of what you're doing, you could just push the feature branch instead, or make a dedicated temporary branch with all the caveats of being "temporary".

(Of course, there's nothing sacred about master per se, it's just that by convention most people expect it to be a stable base from which everyone can pull.)

Note that branches do not necessarily correlate with your features.  Git is for tracking history and thus commits don't necessarily happen in a logical and neat way sometimes.


问:
Introducing functional programming constructs in non-functional programming languages
This question has been going through my mind quite a lot lately and since I haven't found a convincing answer to it I would like to know if other users
of this site have thought about it as well.

In the recent years, even though OOP is still the most popular programming paradigm, functional programming is getting a lot of attention. I have only
used OOP languages for my work (C++ and Java) but I am trying to learn some
FP in my free time because I find it very interesting.

So, I started learning Haskell three years ago and Scala last summer. I plan to
learn some SML and Caml as well, and to brush up my (little) knowledge of Scheme. Well, a lot of plans (too ambitious?) but I hope I will find the time
to learn at least the basics of FP during the next few years.
What is important for me is how functional programming works and how / whether
I can use it for some real projects. I have already developed small tools in Haskell.

In spite of my strong interest for FP, I find it difficult to understand why
functional programming constructs are being added to languages like C#, Java, C++, and so on. As a developer interested in FP, I find it more natural to
use, say, Scala or Haskell, instead of waiting for the next FP feature
to be added to my favourite non-FP language.
In other words, why would I want to have only some FP in my originally
non-FP language instead of looking for a language that has a better support
for FP?

For example, why should I be interested to have lambdas in Java if I can switch
to Scala where I have much more FP concepts and access all the Java libraries
anyway?
Similarly: why do some FP in C# instead of using F# (to my knowledge,
C# and F# can work together)?

Java was designed to be OO. Fine. I can do OOP in Java (and I would like to keep using Java in that way). Scala was designed to support OOP + FP. Fine: I can use a mix of OOP and FP in Scala. Haskell was designed for FP: I can do FP in Haskell. If I need to tune the performance of a particular module, I can
interface Haskell with some external routines in C.

But why would I want to do OOP with just some basic FP in Java?

So, my main point is: why are non-functional programming languages being extended with some functional concept?
Shouldn't it be more comfortable (interesting, exciting, productive) to
program in a language that has been designed from the very beginning to
be functional or multi-paradigm? Don't different programming paradigms
integrate better in a language that was designed for it than in a language
in which one paradigm was only added later?

The first explanation I could think of is that, since FP is a new concept
(it isn't new at all, but it is new for many developers), it needs to be
introduced gradually. However, I remember my switch from imperative to OOP:
when I started to program in C++ (coming from Pascal and C) I really had to
rethink the way in which I was coding, and to do it pretty fast.
It was not gradual. So, this does not seem to be a good explanation to me.

Or can it be that many non-FP programmers are not really interested in
understanding and using functional programming, but they find it practically
convenient to adopt certain FP-idioms in their non-FP language?

IMPORTANT NOTE

Just in case (because I have seen several language wars on this site):
I mentioned the languages I know better, this question is in no way
meant to start comparisons between different programming
languages to decide which is better / worse.

Also, I am not interested in a comparison of OOP versus FP (pros and cons).
The point I am interested in is to understand why FP is being introduced
one bit at a time into existing languages that were not designed for it
even though there exist languages that were / are specifically designed
to support FP.

答:
Who's to say that multiple paradigms can't coexist?  There are number of hybrid languages that bridge the gap between OOP and FP like F# and Scala.

The trouble is the last couple decades made OOP the industry standard and so the majority of folks in the industry understand designing software with objects.  FP offers some low-hanging fruit (ideas such as LINQ) that can be immediately useful in the OO world.  By offering the low-hanging fruit first, programmers can remain productive and gradually cross the bridge, learning to apply FP ideas at their own pace.  This gradual induction into the FP paradigm would not be possible if programmers were forced to embrace the entire paradigm all at once -- e.g. dive straight into Haskell.


问:
Passing functions into other functions as parameters, bad practice?
We've been in the process of changing how our AS3 application talks to our back end and we're in the process of implementing a REST system to replace our old one.

Sadly the developer who started the work is now on long term sick leave and it's been handed over to me. I've been working with it for the past week or so now and I understand the system, but there's one thing that's been worrying me. There seems to be a lot of passing of functions into functions. For example our class that makes the call to our servers takes in a function that it will then call and pass an object to when the process is complete and errors have been handled etc.

It's giving me that "bad feeling" where I feel like it's horrible practice and I can think of some reasons why but I want some confirmation before I propose a re-work to system. I was wondering if anyone had any experience with this possible problem?

答:
This is not a bad thing. In fact, it is a very good thing.

Passing functions into functions is so important to programming that we invented lambda functions as a shorthand. For example, one may use lambdas with C++ algorithms to write very compact yet expressive code that allows a generic algorithm the ability to use local variables and other state to do things like searching and sorting.

Object-oriented libraries may also have callbacks which are essentially interfaces specifying a small number of functions (ideally one, but not always). One can then create a simple class that implements that interface and pass an object of that class through to a function. That is a cornerstone of event-driven programming, where framework-level code (perhaps even in another thread) needs to call into an object to change state in response to a user action. Java's ActionListener interface is a good example of this.

Technically, a C++ functor is also a type of callback object which leverages syntactic sugar, operator()(), to do the same thing.

Finally, there are C-style function pointers which should only be used in C. I will not go into detail, I just mention them for completeness. The other abstractions mentioned above are far superior and should be used in languages that have them.

Others have mentioned functional programming and how passing functions is very natural in those languages. Lambdas and callbacks are the way procedural and OOP languages mimic that, and they are very powerful and useful.


问:
How can if (sscanf(buf, "%i", &mode) != 1 || TRUE) be rewritten to if (TRUE)?
I got lost in the opening of this post on reddit.

How can if (sscanf(buf, "%i", &mode) != 1 || TRUE) be rewritten to if (TRUE)?  Does this assume that the sscanf never fails?

答: The author of the code calls sscanf and then ignores its return value assuming it is true. You can replace the code with 'if (TRUE)' provided that you call sscanf first.</p>


问:
How to manage security of these self hosted web apis, to ensure that the request coming for accessing data is authenticated?
Let's pretend I am going to work on an enterprise application. Say I have 11 modules in the application and I would have to develop Dashboards for every role in the organization for whom I are going to develop application.

We Decided to use Asp.Net Web Api and return json data from our apis.

We are going to include 11 Self hosted web apis projects in our application (one self hosted web api) for every module.

All 11 modules are connected to one Sql server 2012 Database.

Then once api is ready we would have to create Business Dashboards (Based upon roles in Organization).

So Now my web api client is Asp.Net Mvc application.Asp.Net mvc will consume those web apis.

Here is the part for whom all explanation is done.

How should I manage Security of all 11 self hosted web apis?

How should I only authenticated request is coming?

If I authenticate user by login and password  and then redirect user to appropriate Dashboard designed for the role that user have and load data by consuming web apis. How should I ensure that the request coming for accessing data is authenticated?

答:
You could use the same principle as Single Sign On (SSO). Your central authentication app can create a token (when authenticating successfully) that will be passed to the appropriate application where it will get re-checked for validity.

You could even integrate a SSO solution that already does all this logic for you.

Later Edit:
Suppose you central authentication app is called Central Authentication. This will be the landing app for all users. This will display a basic login screen. The logic will be as follows:

Someone enters his/hers credentials in the Central Authentication app

Your backend Controller will check the user name and password against the known users (this depends on where you store your users: a table, Active Directory, remote web service call, etc)

If the authentication is successfull, your application will generate a token, let's call it AUTH_TOKEN based on some criteria. A simple example will be: a simple UUID generator, hash(user+pwd+timestamp+random stuff), etc.

As you have a common DB for all apps, you can save this token into the DB

You redirect to the intended application and also pass this AUTH_TOKEN in the url

Once you lend into the intended application, you first check if the token is valid

If the token is valid, you let the user access the app, otherwise you print a nice message.

Of course, this is just a basic example. You can add further functionality like token expiry, more secure generation of token, etc.