问:
Do wildcards in Java generics restrict or increase flexibility?
I have read many sources about wildcards and Java generics. Even though I have seen many explanations and answers, none of them seems correct.

The question is very simple: Do wilcards in Java generics increase flexibility?

My understand is "No". Wildcards in Java generics (wilcards) actually decrease flexibility.
When I first looked at and used Java generics mechanism, I rarely/never used wildcards. Very often I saw and used the form <T> abc(T xt). One day I got a test question about super and later I started looking at wildcards more closely.

Many sources and in particular: Effective Java 2nd gives an example as follows to show how wildcards increase flexibility.

```<code>public class Stack<E> {
    ...
    public void pushAll(List<E> list) {...}
    ...
}
</code>```

The books goes on and says that since we should be able to use List of anything extending E as argument to pushAll(List<E> list), this is not flexible enough. Therefore, the book suggest changing the signature of the method to pushAll(List<? extends E> list). Now if E is Number then we can even use List<Integer> as argument for pushAll(List<? extends Number> list). And that we have increased flexibility (of the API).

My understanding is that the other solution is not to use wildcards but to use the regular typing. In that case, if we change the method signature to

```<code>public <T extends E> void pushAll(List<T> list)
</code>```

we will achieve the same thing that the wildcard version wants to achieve.
And now in the body of the method, not only we can read from list, we can also write into it. If we use the the wildcard version, we cannot write into that list any value other than null. So in this view, wildcards actually decrease flexibility, not increase.

All in all, it looks to me that wildcards are actually used to decrease flexibility so that <? extends X> discourages people from writing into the object while <? super X> discourages people from reading the object (try it and you will get only Object as type of the returned value). The following example illustrates the <? super X> case.

```<code>public void popAll(List<? super E> list) {
    Object x = list.get(0) // Only get Object as type here, reading is discouraged
}
</code>```

We can change the signature to public <T extends E> void popAll(List<T> list).
Now we can write or read as we want. There is no restriction.

So to sum up: All usages of wildcards can be substituted by typed parameter in the manner of <T extends E> (so there can be no need for the keyword super) . Using wildcards, we lose flexibility in the ability to both read and write into the object. Therefore, wildcards decrease flexibility.

Is it therefore true that wildcards in Java actually decrease flexibility?  If not, how is my reasoning flawed?

[My question is flawed as per missing the cases as mentioned by @Doval in the comment under his answer.]

答:
My understanding is that the other solution is not to use wildcards but to use the regular typing. In that case, if we change the method signature to (...) And now in the body of the method, not only we can read from list, we can also write into it. If we use the the wildcard version, we cannot write into that list any value other than null. So in this view, wildcards actually decrease flexibility, not increase.

The problem is that you're assuming the increased flexibility is for the person writing the function; it's for the person using the function. The more flexibility the implementation gives up, the more flexibility the caller gains. The restrictions on the implementation are guarantees for the caller.

Case in point, when you change pushAll(List<E>) to pushAll(List<? extends E>), the implementer can no longer assume that he knows the precise type stored in the list, and that is why you can't safely write to the list. But because of that, the caller is now free to to pass any list whose elements are a subtype of E, whereas before he could only pass lists of E.

You claim that if you change pushAll to <T extends E> void pushAll(List<T>) you can write to the list, but that's not true in this case. You don't know what class T is ahead of time, so you can't possibly create a T to insert into the list. The only way you could possibly add a T to the list is if the caller gave it to you. That's why Effective Java argues that you should replace type parameters with wildcards if they only appear once in the method; the main purpose of type parameters is to allow you to give an unknown type a name so you can refer to it more than once.

All in all, it looks to me that wildcards are actually used to decrease flexibility so that  discourages people from writing into the object while <? super X> discourages people from reading the object (try it and you will get only Object as type of the returned value). (...) We can change the signature to public <T extends E> void popAll(List<T> list). Now we can write or read as we want. There is no restriction.

You can't just swap super for extends. Let's say you have a Stack<Number>. What's going to happen if you pass a List<Integer> to popAll and the stack tries to insert a Double into the list? Likewise, suppose you pass a List<Object> to pushAll; what's going to happen if the list has a String and you try to insert it into a stack of numbers? Bad things. That's why you use ? extends E when you want to read from the collection and ? super E when you plan on writing to it; it's the only safe way to do it. (There's a mnemonic for remembering which to use: PECS. Producer extends, consumer super.)

Besides, type parameters can't have lower bounds (you can't say T super SomeClass) so you're forced to use a wildcard for super.


问:
Relation between object orientation and algorithms
As I read some algorithms textbooks, they are full of clever procedures for some problems (sorting, shortest path) or some general methods (recursive algorithms, divide and conquer, dynamic programming...). I found few traces of object oriented programming there; (Why they are more procedure-oriented?).

Then I was thinking:

What is the relation between algorithms and OOP? Are they two independent topics?

Are there some problems which can only be presented and solved by OOP?

How can OOP help algorithms? Or in which direction it can affect it?

答:
Alexander Stepanov is the original creator of the C++ Standard Template Library, (STL), which is the foundational algorithm library for C++. C++ is a multi-paradigm language that includes "Object Oriented" features, but Alexander Stepanov has this to say about Object Orientation:

http://www.stlport.org/resources/StepanovUSA.html

STL is not object oriented. I think that object orientedness is almost as much of a hoax as Artificial Intelligence. I have yet to see an interesting piece of code that comes from these OO people.

I find OOP technically unsound. It attempts to decompose the world in terms of interfaces that vary on a single type. To deal with the real problems you need multisorted algebras - families of interfaces that span multiple types. I find OOP philosophically unsound. It claims that everything is an object. Even if it is true it is not very interesting - saying that everything is an object is saying nothing at all. I find OOP methodologically wrong. It starts with classes. It is as if mathematicians would start with axioms. You do not start with axioms - you start with proofs. Only when you have found a bunch of related proofs, can you come up with axioms. You end with axioms. The same thing is true in programming: you have to start with interesting algorithms. Only when you understand them well, can you come up with an interface that will let them work.

I spent years trying to find some use for inheritance and virtuals, before I understood why that mechanism was fundamentally flawed and should not be used.

Stepanov expressed his algorithm library not with Objects, but with Generic Iterators.

ContentLicense: CC BY-SA 3.0


问:
Should log/data files be stored in the database?
I'm working on a project where we produce lots of data in the form of simple .txt files. These usually contain a set of columns that will later be loaded in to Matlab to be analysed. I've implemented an application that uses a database to store information about the person who uses the application and should be able to match that information to the results that are created in the .txt files. The files are long; nearing 10000 rows and with 3-5 columns.

My current application design simply aims to link a query to the database with the file using an Id which works fine provided the files are put in a specific folder and kept there on the server so that the database can always find them.

Should I have designed a way to store the rows and rows of data in the database even though it would just be 100000s of numbers linked to one or two users and session Ids? What is the best practice in this situation.

答:
By storing the files on the file system there is a possibility of things becoming out of sync.  For example, if some process removes the file, or if the data is not saved in the database, there could be mismatches.  In this case it is hard(er) to make the transaction atomic because data is in two sources.  This is not ideal.

If you store all the data (including the file) in the database the transaction will have ACID properties as it will either succeed or fail.  You get this for free because RDMS systems are built this way.  So, the best practice is to store the file in the database.

For the second point, if the users only need is to pull thier data, then just storing the file is acceptable.  However, if thier is a need to query all the data inputted by the users, then I would take the data in the files, extract it and store it relationally in the database so it can be queried across all users.  I am not exactly sure of your application's requirements so either method would be acceptable depending on the application's needs.


答:
you have a problem.

The business domain model describes your problem, and the concepts from the problem domain you are going do be dealing with.

Algorithms describe the way you are going to solve your problems, conceptually; what will your implementation look like; and how do you deal with your problem after you translated it into "Computer Science" terms.

Programming paradigm whether OOP, Functional, Logical, Procedural, or even Non-Structured, describe how are you going to structure your solution, which form is it going to take, which "Software Engineering" concepts are you going do employ, and which "Programming Language Theory" concepts you are going to employ.

To put it more simply, algorithms describe in general your solution to the problem ("This is what I'm going to do"). While programming paradigm deals with your actual implementation ("This is how I'm going to do it").

Title: Relation between object orientation and algorithms

Body:
As I read some algorithms textbooks, they are full of clever procedures for some problems (sorting, shortest path) or some general methods (recursive algorithms, divide and conquer, dynamic programming...). I found few traces of object oriented programming there; (Why they are more procedure-oriented?).

Then I was thinking:

What is the relation between algorithms and OOP? Are they two independent topics?

Are there some problems which can only be presented and solved by OOP?

How can OOP help algorithms? Or in which direction it can affect it?


问:
Replace repeated timestamp with variable in tests
I have couple hundred tests and I work with date/time a lot. In some tests, I aim for output format, elsewhere, I check date ranges. Therefore, my tests have lots of these:

```<code>FactoryGirl.create(:foo, ended_at: Time.zone.local(2014, 5, 5, 22, 15))
</code>```

I thought, maybe there's a shortcut to these, since in some test files, I only work with few timestamps.

```<code>FactoryGirl.create(:foo, ended_at: may_5_22_15)
</code>```

Where may_5_22_15 would be defined in method or using let.

Is this a good way to go?

Update: More context (thanks @Snowman for pointing out).

Motivation for this is to improve readability of testsuite. It makes it easier to me to read "Foo ended at May 5th by 22:15" rather than parsing a bunch of numbers in Time constructor.

The model has bunch of date/time attributes (ended_at, started_at, closed_at...) and the more specs I write, the more Time constructors I use and re-use. So I thought maybe I could do something like this:

```<code>let(:may_5_22_15) { Time.zone.local(2014, 5, 5, 22, 15) }
</code>```

What I'd like to know is whether this is a good practice or not, in terms of test suite maintenance, readability or if there are any reasons why not to do it.

答: Named constants are often a better idea than magic numbers.  In this context, however, there's not a lot of magic involved.  On the other hand, in some languages, the time-value constructor uses a zero-ordinal value for only some of its values (e.g., JavaScript's Date()'s month number), or have illogical behavior such as accepting out-of-range values as non-integral multiples of the next-higher order (again, JavaScript's Date()).  In such environments, a named constant for a timestamp makes excellent sense.


问:
Database structure for links between objects of same class
I have seen elsewhere that it is a nice design to implement links between objects in a database as a separate object. This makes a clean way to have multiple objects of one class to be linked to an object of another class, as opposed to adding a "links" property to an object, which then gets populated with, say a CSV list of other objects that are linked.

Now I want to go through my music collection (MP3) and find differently encoded versions of the same recording (via audio fingerprinting - think of the same song ripped twice with a different bit rate for example). Now I am not sure how to design the link objects, since they link objects of the same class. I could just do something like

```<code>id songA songB
</code>```

but then if I want to search for all matches for a particular song, I will have to go through both songA and songB to find possible links. Is there a smarter way to do this?

答:
This doesn't call for a linking entity (although they very useful for N:M relations and infinitely better than trying to cram a list of things into a single field or multiple fields!).

What you want is a SONG entity that can be referenced by multiple RECORDING entities. A SONG has a title, artist etc., while a RECORDING might have a bit rate, loudness, file date etc. The RECORDING would have a single foreign key to the SONG table. That's how you express N:1 associations.


问:
Which events to store with event-sourcing?
I'm planning out the events that my application will be creating, but am running into problems with my design.  I believe I'm not applying the event-sourcing concepts correctly.

Take the bank account example.  My application receives a command to deposit cash, accepts it, and then creates the event CashDeposited.  Based on the business logic, the higher account balance triggers the interest rate to be increased, so I create the event InterestRateChanged.

Now if I record both of these events to my event store, upon restart, both events will be replayed.  But because the CashDeposited event triggers the InterestRateChanged event, won't the InterestRateChanged be replayed twice: once from the event store and once as a result of CashDeposited being replayed?

答:
I recommend a proper implementation of Gateway pattern. As Martin Fowler states:

Many of the advantages of Event Sourcing stem from the ability to
  replay events at will, but if these events cause update messages to be
  sent to external systems, then things will go wrong because those
  external systems don't know the difference between real processing and
  replays.

To handle this you'll need to wrap any external systems with a
  Gateway. This in itself isn't too onerous since it's a thoroughly good
  idea in any case. The gateway has to be a bit more sophisticated so it
  can deal with any replay processing that the Event Sourcing system is
  doing.

E.g.:

```<code>public class VerySimpleGateway()
{
    public bool IsReplayMode;

    public void FilterProcessingEvent(IEvent event)
    {
        if (IsReplayMode) {
            // for example delete event from event processing queue or adjust event state itself
            // next processing component in the pipeline is informed not to touch this event
        }
    }
}
</code>```

In event processing pipeline you can treat such gateway as a step in Chain-responsibility pattern.

Body:
I recommend a proper implementation of Gateway pattern. As Martin Fowler states:

Many of the advantages of Event Sourcing stem from the ability to
  replay events at will, but if these events cause update messages to be
  sent to external systems, then things will go wrong because those
  external systems don't know the difference between real processing and
  replays.

To handle this you'll need to wrap any external systems with a
  Gateway. This in itself isn't too onerous since it's a thoroughly good
  idea in any case. The gateway has to be a bit more sophisticated so it
  can deal with any replay processing that the Event Sourcing system is
  doing.

E.g.:

public class VerySimpleGateway()
{
    public bool IsReplayMode;

    public void FilterProcessingEvent(IEvent event)
    {
        if (IsReplayMode) {
            // for example delete event from event processing queue or adjust event state itself
            // next processing component in the pipeline is informed not to touch this event
        }
    }
}

In event processing pipeline you can treat such gateway as a step in Chain-responsibility pattern.


问:
Are #regions an antipattern or code smell?
C# allows the use of #region/#endregion keywords to make areas of code collapsible in the editor. Whenever I do this though I do it to hide large chunks of code that could probably be refactored into other classes or methods. For example I have seen methods that contain 500 lines of code with 3 or 4 regions just to make it manageable.

So is judicious use of regions a sign of trouble? It seems to be so to me.

答:
I believe the are a anti pattern and frankly think they should be eliminated. But if you are in the unfortunate situation of working in a place where they are a standard Visual Studio offers an awesome tool to minimize the amount you would like to vomit everytime you see a region I Hate #Regions

This plugin will max the font size of the regions really small. They will also be expanded so you won't have to hit ctr+m+l to open all regions. It doesn't fix this form of code cancer but it does make it bearable.


答:
I think Jon Raynor makes a good point about the safety and consistency of your data being better in a database. I think a database could make application management easier in some ways (fewer data files to be concerned with,  as well as easier disaster recovery or failover capability)

But, I don't think a relational database (such as MySQL) is required for the data you are storing - I think it would add overhead which you don't need.

Instead you might find a NoSQL database, which does not use a fixed schema more useful. In addition, it might provide additional capabilities to use the data.

A useful comparison of features is here: http://www.thegeekstuff.com/2014/01/sql-vs-nosql-db/

Title: Should log/data files be stored in the database?

Body:
I'm working on a project where we produce lots of data in the form of simple .txt files. These usually contain a set of columns that will later be loaded in to Matlab to be analysed. I've implemented an application that uses a database to store information about the person who uses the application and should be able to match that information to the results that are created in the .txt files. The files are long; nearing 10000 rows and with 3-5 columns.

My current application design simply aims to link a query to the database with the file using an Id which works fine provided the files are put in a specific folder and kept there on the server so that the database can always find them.

Should I have designed a way to store the rows and rows of data in the database even though it would just be 100000s of numbers linked to one or two users and session Ids? What is the best practice in this situation.


问:
Understanding RESTful web services
I've been trying to understand how RESTful web services work and I've come up with a series of doubts and questions for which I have been unable to find an answer. First of all and to make sure I am correctly understanding what this is all about, the following diagram summarizes what a RESTful architecture for a small website could look like:

The first server basically contains a set of services identified by URL's. Those services obtain information from different databases and provide it to someone asking through a REST API (JSON) over http or https. On another server, a web application in an MVC style interacts with those services through their URL's upon user requests.

Is my understanding correct?

How do web applications such as facebook cope with the delays in getting responses when handling multiple services?

How does one make sure that only certain entities are allowed access to services (in this example, how does Server 1 authenticate Server 2)?

Is it common to use these kinds of architectures for mobile applications too?

When mixing this type of architecture with AJAX, are the AJAX calls done directly to the services or do they go through the main web application controller?

答:
To echo what MainMan said, there are two different concepts at play here, REST and microservices.

Your diagram is a micro-service set up. You can do this with RESTful architecture, or with any other architecture. While micro-services and REST are often used together they are not the same thing.

REST is a way of thinking about communication between clients and servers in order to ensure loose coupling between client and server.

It is a different paradign to the more traditional Remote Procedure Call paradign where the client issues command to the server to carry out. With RPC the client has to be aware of what commands the server understands, which can change at work on the server evolves.

With a REST architecture you limit the communication between client and server simply to commands to transfer a representation of a piece of data. HTTP is a RESTful architeture and the only verbs in HTTP are GET, PUT, POST, DELETE etc.

As an example of the difference say your service is about photo editing. In a traditional RPC setup the client might issue the server a whole lot of commands to update a photo. The client might say "Ok, first blur the image, then rotate it, then crop it". The client has issued 3 commands to the server.

The problem with that is that it couples the client and server together, in that the client must know what commands the server understands. Say later you change the command from "blur" to "defocus". You have to update every single client. Or say a client wants to do a "blur" but the server it is talking to only has version 0.1 of the server code and doesn't understand "blur". You have to update the server every time a client wants to do something new.

In REST what happens is instead the client says "Ok server give me a copy of the photo". The client gets/downloads a copy of the photo and then carries out any number of changes client side.

The client then says "Ok, server store this new state of the photo".

All the client and servers need to know is commands to get and push back the data. HTTP is a REST protocol and if you look at the HTTP verbs they concern themselves only with the getting and putting of resources.

So REST isn't really anything to do with microservice architecture, but is instead a way of thinking about how your client and server are going to handle commands and data between each other.

Title: Understanding RESTful web services


问:
Benefits of using .NET style delegates compared to custom ones
I know about C# events and delegates. I find them incredibly useful for event-driven sub-systems. One thing I don't understand, however, is why all the .NET documentation for events uses a very specific pattern for delegates:

```<code>public class Foo
{
    public class CustomEventArgs : System.EventArgs
    {
        ...
    }

    public delegate void CustomEventHandler(object sender, EventArgs e);
    public event CustomEventHandler CustomEvent;

    public void OnCustomEvent(int x, float y, bool z)
    {
        if (CustomEvent != null)
            CustomEvent(this, new CustomEventArgs(x, y, z));
    }
}
</code>```

I find this method of declaring and using delegates incredibly unsecure and clunky compared to using custom delegates. For example:

```<code>public class Foo
{
    public delegate void CustomEventHandler(Foo foo, int x, float y, bool z);
    public event CustomEventHandler CustomEvent;

    public void OnCustomEvent(int x, int y, int z)
    {
        if (CustomEvent != null)
            CustomEvent(this, x, y, z);
    }
}
</code>```

Besides the obvious advantage of "It's the pattern most familiar to .NET programmers", I fail to see any other practical advantages to using delegates with the void CustomEventHandler(object sender, CustomEventArgs e) signatures as opposed to custom delegates. Mainly, you have the following advantages with custom delegates:

You can guarantee the sender is of a specific type.

You don't need a whole new class just to pass the event data, leading to messier code and name pollution

I would be interested to know if there are any other advantages to using the .NET pattern for events and delegates that I might be missing.

Edit:

Mainly as a response to @MainMa, I wanted to give a more concrete example. The example is a simple representation of a character with a concept of health and death. The character throws events when its hurt, or dies. Consider the scenario below, using custom delegates:

```<code>public class Character
{
    public delegate void DeathEventHandler(Character character);
    public delegate void HurtEventHandler(Character character, float damage);

    public event DeathEventHandler DeathEvent;
    public event HurtEventHandler HurtEvent;

    public bool IsDead { ... }

    public void ApplyDamage(float damage)
    {
        ...
        OnHurt(damage);
        ...
        if (IsDead)
            OnDeath();
    }

    public void OnHurt(float damage)
    {
        if (HurtEvent != null)
            HurtEvent(this, damage);
    }

    public void OnDeath()
    {
        if (DeathEvent != null)
            DeathEvent(this);
    }
}
</code>```

To me, this is simple. It separates concerns, and enforces encapsulation. A handler that is only concerned about the death of a character doesn't need to know how much damage was applied to the character before death. So on and so forth.

Now compare this to the .NET pattern:

```<code>public class Character
{
    public class CharacterHurtEventArgs : EventArgs
    {
        public float Damage { ... }
        public bool Dead { ... }
    }

    public event EventHandler<CharacterHurtEventArgs> HurtEvent;
    public event EventHandler<EventArgs> DeathEvent; // No args ...?

    // ... The rest is the same story as above more or less ...
}
</code>```

Using this, I've just added an extra class. The handler still needs different delegates for these events, and there is no guarantee that the object which died was a character. Anything could throw this.

Of course, going by @MainMa's suggestion, we could change this into:

```<code>public class Character
{
    public class HealthConditionEventArgs : EventArgs
    {
        public float Damage { ... }
        public bool Dead { ... }
        public float Hitpoints { ... }
        ...
    }

    public event EventHandler<HealthConditionEventArgs> HealthConditionChangedEvent;

    public void ApplyDamage(float damage)
    {
        ...
        HealthConditionChangedEventArgs e = new HealthConditionChangedEventArgs();
        ...
        OnHealthConditionChanged(e);
        ...
    }

    public void OnHealthConditionChanged(HealthConditionEventArgs e)
    {
        if (HealthConditionChangedEvent != null)
            HealthConditionChangedEvent(e);
    }
}
</code>```

This is slightly neater, but it eliminates separation of concerns. Now if the handler only cares about death, it will have to receive all hurt events. Of course, we could have separate events taking in the same event args, but you'd still be passing around the entire character health condition as part of the event. Again, if you care only about death, there is no need for the handler to know any more than the fact that the character died.

In my opinion, the first example, however, resolves all these encapsulation issues. Discrete delegates for discrete events, with only the necessary information passed in each event. No new classes either.

答:
Let's imagine an example of a presentation layer. The layer has mouse interactions: every time the user moves a mouse, an event telling which mouse moved (imagine the user may have multiple mice) and how the mouse moved can be raised.

With your approach, the draft code would be:

```<code>public delegate void MouseMovedHandler(
    PresentationLayer l, Guid mouseId, int fromX, int fromY, int toX, int toY);
</code>```

It will obviously be quickly refactored into:

```<code>public delegate void MouseMovedHandler(
    PresentationLayer l, Guid mouseId, Coord from, Coord to);
</code>```

But then, you'll find that you want to know, for instance, the distance between from and to. So you'll create a Line class, defined by two points, and your delegate will become:

```<code>public delegate void MouseMovedHandler(PresentationLayer l, Guid mouseId, Line motion)
</code>```

Better. Now, what if we want to be able to make a difference between a simple line and a motion of a specific, identified mouse? Right, we'll end up creating the class:

```<code>class MouseMotion : Line
{
    public Mouse Mouse { get; }
    public Line Motion { get; }
    ...
}

public delegate void MouseMovedHandler(PresentationLayer l, MouseMotion motion)
</code>```

Now, there is a location in your app where you need to track every possible input: mouse motion, mouse button clicks, keyboard strokes. You need that because your application starts background processing when the user is not doing anything, but should stop it and free the resources to the UI if the user is using your app.

This means that now, you need something common between MouseMotion, MouseButtonChange and KeyboardStroke. Something like IEvent. Or wouldn't it be easier to simply use EventArgs?

So you end up with:

```<code>class MouseMotionEventArgs: EventArgs { ... }
public delegate void MouseMovedHandler(PresentationLayer l, MouseMotionEventArgs motion)
</code>```

Except that you could avoid the delegate, as explained at the beginning of the answer. You can now either stick with the delegate in order to have your strongly typed PresentationLayer you probably don't need most of the time, or replace it with a lousy object by using EventHandler<MouseMotionEventArgs>.

The previous version of the answer, for the sake of completeness:

Is there a reason you create a CustomEventHandler instead of using EventHandler<CustomEventArgs>?

With the generic EventHandler<T>, the code starts looking like this:

```<code>public class Foo
{
    public event EventHandler<3DPointChangedEventArgs> CustomEvent;

    public void OnCustomEvent(3DPoint point)
    {
        if (CustomEvent != null)
        {
            CustomEvent(this, (3DPointChangedEventArgs)point);
        }
    }
}
</code>```

Now, compare it to the code you suggested:

Yours is longer. Chances are, your colleagues will refactor x, y and z into 3DPoint object, making it a bit shorter.

Yours doesn't match the convention used in .NET Framework. Therefore, it will be difficult to know how to use it.

The one used in .NET Framework makes it possible “to write a single event handler for multiple events, regardless of sender or event.”

Talking specifically about name pollution, having *EventArgs classes is not that bad. Those names are usually very clear and express the intention of the author and cannot be confused with other business objects.

Answering your last edit, there are three points to consider:

It is not necessarily useful to separate the death from the health. The most basic representation of health could be a number; for instance, 0.0 can represent death and 100.0 can correspond to the full health.

Of course, a number would better be replaced by Health class which can then contain business rules which can be modified through time. For example, if it is a game, further features may include additional health slots, making it possible to have, say, 120% of health.

This may create a performance issue: one event less means that if something is listening to the death events, it will now be notified about all the health change events. I wouldn't be concerned about that early, and wait until it becomes an actual bottleneck. After all, what if the performance becomes even better, now that we don't have a condition in ApplyDamage()?

If the author decides to keep both events, death event can use EventArgs, making it possible to use EventArgs.Empty. This makes one delegate less to write.

Who listens to the event? Let's imagine the world listens to it in order to remove objects a few minutes after their death (which makes sense, since objects may not be aware of the world, and so won't be able to remove themselves from it).

This also means that we don't really care if the dead object is a Character or a Trebuchet or a WarShip or a Horse : Animal. This means that it is OK to lose types when transmitting the information through the event: the removal will be the same for a paladin or a sheep.

Here's the final result which applies the point 1 and 3:

```<code>public class Health
{
    private double value;

    public Health(double value) { ... }

    public void ApplyDamage() { ... }
}

public class Character
{
    public event EventHandler<HealthEventArgs> HealthChanged;

    public Health Health { get { return this.health; } }

    public void ApplyDamage(double damage)
    {
        ...
        this.health.ApplyDamage(damage);
        ...
    }

    public void OnHealthChange(float damage)
    {
        if (HurtEvent != null)
        {
            HurtEvent(this, damage);
        }
    }
}
</code>```

The events handling can then be done like this, making abstraction of the type of the world object being removed:

```<code>public class World
{
    public void MarkAsDead(object worldObject)
    {
        // Wait for five minutes.
        this.elements.Remove(worldObject);
    }
}
</code>```

Body:
Let's imagine an example of a presentation layer. The layer has mouse interactions: every time the user moves a mouse, an event telling which mouse moved (imagine the user may have multiple mice) and how the mouse moved can be raised.

With your approach, the draft code would be:

public delegate void MouseMovedHandler(
    PresentationLayer l, Guid mouseId, int fromX, int fromY, int toX, int toY);

It will obviously be quickly refactored into:

public delegate void MouseMovedHandler(
    PresentationLayer l, Guid mouseId, Coord from, Coord to);

But then, you'll find that you want to know, for instance, the distance between from and to. So you'll create a Line class, defined by two points, and your delegate will become:

public delegate void MouseMovedHandler(PresentationLayer l, Guid mouseId, Line motion)

Better. Now, what if we want to be able to make a difference between a simple line and a motion of a specific, identified mouse? Right, we'll end up creating the class:

class MouseMotion : Line
{
    public Mouse Mouse { get; }
    public Line Motion { get; }
    ...
}

public delegate void MouseMovedHandler(PresentationLayer l, MouseMotion motion)

Now, there is a location in your app where you need to track every possible input: mouse motion, mouse button clicks, keyboard strokes. You need that because your application starts background processing when the user is not doing anything, but should stop it and free the resources to the UI if the user is using your app.

This means that now, you need something common between MouseMotion, MouseButtonChange and KeyboardStroke. Something like IEvent. Or wouldn't it be easier to simply use EventArgs?

So you end up with:

class MouseMotionEventArgs: EventArgs { ... }
public delegate void MouseMovedHandler(PresentationLayer l, MouseMotionEventArgs motion)

Except that you could avoid the delegate, as explained at the beginning of the answer. You can now either stick with the delegate in order to have your strongly typed PresentationLayer you probably don't need most of the time, or replace it with a lousy object by using EventHandler<MouseMotionEventArgs>.

The previous version of the answer, for the sake of completeness:

Is there a reason you create a CustomEventHandler instead of using EventHandler<CustomEventArgs>?

With the generic EventHandler<T>, the code starts looking like this:

public class Foo
{
    public event EventHandler<3DPointChangedEventArgs> CustomEvent;

    public void OnCustomEvent(3DPoint point)
    {
        if (CustomEvent != null)
        {
            CustomEvent(this, (3DPointChangedEventArgs)point);
        }
    }
}

Now, compare it to the code you suggested:

Yours is longer. Chances are, your colleagues will refactor x, y and z into 3DPoint object, making it a bit shorter.

Yours doesn't match the convention used in .NET Framework. Therefore, it will be difficult to know how to use it.

The one used in .NET Framework makes it possible “to write a single event handler for multiple events, regardless of sender or event.”

Talking specifically about name pollution, having *EventArgs classes is not that bad. Those names are usually very clear and express the intention of the author and cannot be confused with other business objects.

Answering your last edit, there are three points to consider:

It is not necessarily useful to separate the death from the health. The most basic representation of health could be a number; for instance, 0.0 can represent death and 100.0 can correspond to the full health.

Of course, a number would better be replaced by Health class which can then contain business rules which can be modified through time. For example, if it is a game, further features may include additional health slots, making it possible to have, say, 120% of health.

This may create a performance issue: one event less means that if something is listening to the death events, it will now be notified about all the health change events. I wouldn't be concerned about that early, and wait until it becomes an actual bottleneck. After all, what if the performance becomes even better, now that we don't have a condition in ApplyDamage()?

If the author decides to keep both events, death event can use EventArgs, making it possible to use EventArgs.Empty. This makes one delegate less to write.

Who listens to the event? Let's imagine the world listens to it in order to remove objects a few minutes after their death (which makes sense, since objects may not be aware of the world, and so won't be able to remove themselves from it).

This also means that we don't really care if the dead object is a Character or a Trebuchet or a WarShip or a Horse : Animal. This means that it is OK to lose types when transmitting the information through the event: the removal will be the same for a paladin or a sheep.

Here's the final result which applies the point 1 and 3:

public class Health
{
    private double value;

    public Health(double value) { ... }

    public void ApplyDamage() { ... }
}

public class Character
{
    public event EventHandler<HealthEventArgs> HealthChanged;

    public Health Health { get { return this.health; } }

    public void ApplyDamage(double damage)
    {
        ...
        this.health.ApplyDamage(damage);
        ...
    }

    public void OnHealthChange(float damage)
    {
        if (HurtEvent != null)
        {
            HurtEvent(this, damage);
        }
    }
}

The events handling can then be done like this, making abstraction of the type of the world object being removed:

public class World
{
    public void MarkAsDead(object worldObject)
    {
        // Wait for five minutes.
        this.elements.Remove(worldObject);
    }
}


答:
Algorithms describe what the computer should do.  Structure describes how the algorithm is laid out [in source code].  OOP is a style of programming which leverages certain "object oriented" structures.

Algorithm books often eschew OOP because they are focused on algorithm, not structure.  Fragments of code which heavily rely on structure tend to be poor examples to put in an algorithm book.  Likewise, OOP books often eschew algorithms because they clutter up the story.  The selling point of OOP is its fluidity, and pegging it to an algorithm makes it appear more rigid.  It's more about the focus of the book than anything else.

In real life code, you will use both side by side.  You can't solve computer problems without algorithms, by definition, and you'll find its hard to write good algorithms without structure (OOP or otherwise).

As an example of where they blur, take Dynamic Programming.  In an algorithm book, you would describe how to take a homogenous dataset in an array and use Dynamic Programming to arrive at a solution.  In an OOP book, you may come across a structure such as Visitor, which is a way to do arbitrary algorithms across a set of heterogeneous objects.  The DP book example could be thought of as a very simple Visitor operating on objects in a generally bottom-up order.  The Visitor pattern could be thought of as the skeleton of a DP problem, but missing the meat and potatoes.  In reality, you will find you often need both together: You use the Visitor pattern to deal with heterogeneity across your dataset (DP is bad at that), and you use DP within the structure of Visitor to organize your algorithm to minimize runtime (Visitor doesn't specify an algorithm).

We also see algorithms operating over the top of design patterns.  Its harder to word examples in a small space, but once you have structure, you start wanting to manipulate that structure, and you use algorithms to do it.

Are there some problems which can only be presented and solved by OOP?

This is a more difficult question to answer than you think it is.  To the first order, there is no computational reason why you need OOP to solve any problem.  The simple proof is that every OOP program gets compiled down to assembly, which is a decidedly non-OOP language.

However, in the greater scheme of things, the answer starts to shy towards yes.  You are rarely limited simply by computing methodologies.  Most of the time there are things like business needs and developer skill that factor into the equation.  Many applications today could not be written without OOP, not because OOP is somehow fundamental to the task, but because the structure provided by OOP was essential for keeping the project on track and on budget.

This does not say that we will never abandon OOP in the future for some funny new structure.  It merely says it is one of the most effective tools in our toolbox for a surprisingly large fraction of programming tasks out there today.  Future problems may cause us to approach development using different structures.  For one, I expect neural nets to require a very different development approach, which may or may not turn out to be "Object Oriented."

I do not see OOP dissapearing in the near future due to the way algorithm designers think.  To date, the usual pattern is that somebody designs an algorithm which doesn't leverage OOP.  The OOP community realizes the algorithm doesn't really fit the OOP structure, and really doesn't need to, so they they wrap the entire algorithm in an OOP structure and start using it.  Consider boost::shared_ptr.  The reference counting algorithms that rest inside shared_ptr are not very OOP friendly.  However, the pattern did not get popular until shared_ptr created an OOP wrapper around it that exposed the capabilities of the algorithms in an OOP structured format.  Now, it's so popular that it made it into the latest spec for C++, C++11.

Why is this so successful?  Algorithms are great at solving problems, but they often require a substantial initial research investment to understand how to use them.  Object Oriented development is very effective at wrapping such algorithms and providing an interface which requires less initial investment to learn.


答:
This is the convention adopted by Winforms, and also some other event handlers in the .NET ecosystem.  It provide two things: the object that caused the event, and some specific event arguments.

One of the reasons it is done this way is because events can be multicast; you can have one event handler handling multiple events, or one event being broadcast to several handlers.  To provide flexibility, the bare object is sent to the event handler, in case we don't actually know what type the object raising the event is.  This convention was created prior to the introduction of generics.

Note that the .NET framework provides a generic version of the Event Handler delegate since .NET 2.0, which provides compile-time type safety.

Title: Benefits of using .NET style delegates compared to custom ones

Body:
I know about C# events and delegates. I find them incredibly useful for event-driven sub-systems. One thing I don't understand, however, is why all the .NET documentation for events uses a very specific pattern for delegates:

```<code>public class Foo
{
    public class CustomEventArgs : System.EventArgs
    {
        ...
    }

    public delegate void CustomEventHandler(object sender, EventArgs e);
    public event CustomEventHandler CustomEvent;

    public void OnCustomEvent(int x, float y, bool z)
    {
        if (CustomEvent != null)
            CustomEvent(this, new CustomEventArgs(x, y, z));
    }
}
</code>```

I find this method of declaring and using delegates incredibly unsecure and clunky compared to using custom delegates. For example:

```<code>public class Foo
{
    public delegate void CustomEventHandler(Foo foo, int x, float y, bool z);
    public event CustomEventHandler CustomEvent;

    public void OnCustomEvent(int x, int y, int z)
    {
        if (CustomEvent != null)
            CustomEvent(this, x, y, z);
    }
}
</code>```

Besides the obvious advantage of "It's the pattern most familiar to .NET programmers", I fail to see any other practical advantages to using delegates with the void CustomEventHandler(object sender, CustomEventArgs e) signatures as opposed to custom delegates. Mainly, you have the following advantages with custom delegates:

You can guarantee the sender is of a specific type.

You don't need a whole new class just to pass the event data, leading to messier code and name pollution

I would be interested to know if there are any other advantages to using the .NET pattern for events and delegates that I might be missing.

Edit:

Mainly as a response to @MainMa, I wanted to give a more concrete example. The example is a simple representation of a character with a concept of health and death. The character throws events when its hurt, or dies. Consider the scenario below, using custom delegates:

```<code>public class Character
{
    public delegate void DeathEventHandler(Character character);
    public delegate void HurtEventHandler(Character character, float damage);

    public event DeathEventHandler DeathEvent;
    public event HurtEventHandler HurtEvent;

    public bool IsDead { ... }

    public void ApplyDamage(float damage)
    {
        ...
        OnHurt(damage);
        ...
        if (IsDead)
            OnDeath();
    }

    public void OnHurt(float damage)
    {
        if (HurtEvent != null)
            HurtEvent(this, damage);
    }

    public void OnDeath()
    {
        if (DeathEvent != null)
            DeathEvent(this);
    }
}
</code>```

To me, this is simple. It separates concerns, and enforces encapsulation. A handler that is only concerned about the death of a character doesn't need to know how much damage was applied to the character before death. So on and so forth.

Now compare this to the .NET pattern:

```<code>public class Character
{
    public class CharacterHurtEventArgs : EventArgs
    {
        public float Damage { ... }
        public bool Dead { ... }
    }

    public event EventHandler<CharacterHurtEventArgs> HurtEvent;
    public event EventHandler<EventArgs> DeathEvent; // No args ...?

    // ... The rest is the same story as above more or less ...
}
</code>```

Using this, I've just added an extra class. The handler still needs different delegates for these events, and there is no guarantee that the object which died was a character. Anything could throw this.

Of course, going by @MainMa's suggestion, we could change this into:

```<code>public class Character
{
    public class HealthConditionEventArgs : EventArgs
    {
        public float Damage { ... }
        public bool Dead { ... }
        public float Hitpoints { ... }
        ...
    }

    public event EventHandler<HealthConditionEventArgs> HealthConditionChangedEvent;

    public void ApplyDamage(float damage)
    {
        ...
        HealthConditionChangedEventArgs e = new HealthConditionChangedEventArgs();
        ...
        OnHealthConditionChanged(e);
        ...
    }

    public void OnHealthConditionChanged(HealthConditionEventArgs e)
    {
        if (HealthConditionChangedEvent != null)
            HealthConditionChangedEvent(e);
    }
}
</code>```

This is slightly neater, but it eliminates separation of concerns. Now if the handler only cares about death, it will have to receive all hurt events. Of course, we could have separate events taking in the same event args, but you'd still be passing around the entire character health condition as part of the event. Again, if you care only about death, there is no need for the handler to know any more than the fact that the character died.

In my opinion, the first example, however, resolves all these encapsulation issues. Discrete delegates for discrete events, with only the necessary information passed in each event. No new classes either.


问:
When, if ever, should I daisy chain functions?
In a program divided up into many functions by which it is intended that they execute themselves one after another, when (if ever) is it preferred to:

A) Execute the functions one after another in main()?

or

B) Execute one function in main(), and have that function daisy chain to the rest of the functions that need to be executed?

To illustrate this

Program FlowChart:

Start -> Make foo -> Do bar? -> True -> Say Goodbye -> End

A:

```<code>void makeFoo() {
    [...]
    return;
}
bool doBar() {
    bool bar;
    [...]
    return bar;
}
void sayGoodbye() {
    [...]
    return;
}
int main {
    makeFoo();
    if (doBar()) {
        sayGoodbye();
    }
    return 0;
}
</code>```

B: (Daisy Chain)

```<code>void makeFoo() {
    [...]
    doBar();
    return;
}
void doBar() {
    bool bar;
    [...]
    if (bar) {
        sayGoodbye();
    }
    return;
}
void sayGoodbye() {
    [...]
    return;
}
int main {
    makeFoo();
    return 0;
}
</code>```

答:
Your methods should do one and one only thing.

For example, is saying good bye a part of doBar?

If yes, your second approach should be used.

If saying good bye should be done after doBar but is not part of doBar, then your first approach is better.

Practical example. A part of an application should read and process data. This is done through five methods:

ConnectToDatabase()

Opens the connection, making it possible to query the database.

GetData()

Retrieves valid, sanitized data from the database.

LoadData()

Loads the data from the database into memory for further processing.

ValidateData()

Makes sure the data is valid: if it's not, throws an exception, since this situation is truly exceptional.

SanitizeData()

Transforms the data in order for it to be processed. Although unsanitized data is still valid, we need to sanitize it to match specific constraints of our processing.

ProcessData()

Processes the data by making some dark magic stuff with it.

Output()

Shows the result of the processed data on the screen. The result contains two charts.

GenerateCharts()

Generates the final charts to be shown to the user.

DisplayGlobalChart()

Displays the first chart on the screen.

DisplayPerMonthChart()

Displays the second chart on the screen.

It looks like ConnectToDatabase(), LoadData() and SanitizeData() are all part of GetData(): when you call GetData(), you don't care if it's loaded from the database of from a flat file, how is it actually loaded or does it require to be sanitized. You just need the data set ready for your work.

It also seems that charts generation and two methods which display the chart can easily go into Output(): again, you don't care how the information should be displayed when you call Output(); you just know that information is not there yet, and now, it should be on the screen.

So far, the calls are:

```<code>GetData()
{
    ConnectToDatabase();
    LoadData();
    SanitizeData();
}

Output()
{
    GenerateCharts();
    DisplayGlobalChart();
    DisplayPerMonthChart();
}

Main()
{
    data = GetData();
    result = ProcessData(data);
    Output(result);
}
</code>```

Remains ValidateData(). This one is tricky. It may be called by SanitizeData(): it makes sense, since before sanitizing a piece of information, one should probably validate it first. On the other hand, it might be that those processes are different enough and one can be called independently from other. In this case, ValidateData() would be rather in GetData(), just before SanitizeData().

Body:
Your methods should do one and one only thing.

For example, is saying good bye a part of doBar?

If yes, your second approach should be used.

If saying good bye should be done after doBar but is not part of doBar, then your first approach is better.

Practical example. A part of an application should read and process data. This is done through five methods:

ConnectToDatabase()

Opens the connection, making it possible to query the database.

GetData()

Retrieves valid, sanitized data from the database.

LoadData()

Loads the data from the database into memory for further processing.

ValidateData()

Makes sure the data is valid: if it's not, throws an exception, since this situation is truly exceptional.

SanitizeData()

Transforms the data in order for it to be processed. Although unsanitized data is still valid, we need to sanitize it to match specific constraints of our processing.

ProcessData()

Processes the data by making some dark magic stuff with it.

Output()

Shows the result of the processed data on the screen. The result contains two charts.

GenerateCharts()

Generates the final charts to be shown to the user.

DisplayGlobalChart()

Displays the first chart on the screen.

DisplayPerMonthChart()

Displays the second chart on the screen.

It looks like ConnectToDatabase(), LoadData() and SanitizeData() are all part of GetData(): when you call GetData(), you don't care if it's loaded from the database of from a flat file, how is it actually loaded or does it require to be sanitized. You just need the data set ready for your work.

It also seems that charts generation and two methods which display the chart can easily go into Output(): again, you don't care how the information should be displayed when you call Output(); you just know that information is not there yet, and now, it should be on the screen.

So far, the calls are:

GetData()
{
    ConnectToDatabase();
    LoadData();
    SanitizeData();
}

Output()
{
    GenerateCharts();
    DisplayGlobalChart();
    DisplayPerMonthChart();
}

Main()
{
    data = GetData();
    result = ProcessData(data);
    Output(result);
}

Remains ValidateData(). This one is tricky. It may be called by SanitizeData(): it makes sense, since before sanitizing a piece of information, one should probably validate it first. On the other hand, it might be that those processes are different enough and one can be called independently from other. In this case, ValidateData() would be rather in GetData(), just before SanitizeData().


答:
Daisy chain when it is clear to the next developer why you did it that way.

"Code is read more often than it is written." -Guido von Rossum, PEP 008

There is no one answer to this, but I can give you a good rule of thumb: If the name of the function implies that its job is to do one function and call another, then it is safe to chain them.

There are times where two functionalities do really need to chain.  Consider the classic example of error handling

```<code>result = doSomething();
if (result == badValue)
    haltAndCatchFire();
</code>```

If this pattern shows up all the time, the next developer is going to get sore reading it over and over.  Worse, they may get lazy or forget, causing unexpected results.  However, haltAndCatchFire on its own is a pretty useful function to have, so we don't want to bury that functionality into doSomething, just to never see it again.  As a solution:

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

Its long, but now it is very clear that you intend to daisy chain.  A developer who does not want to follow you into doSomething can generally assume that you'll call haltAndCatchFire if anything goes wrong, so you have successfully transmitted information to the next developer.  They can keep reading main() without having to dodge and weave through multiple functions.

Your naming choice is up to you, as long as it is clear.  As an example, on one suite of software I developed, there was a pattern:

```<code>int getValue();
int tryGetValue();
</code>```

It was understood (social contract) that getValue() should call exception handling functions if something goes wrong.  TryGetValue should just return (often returning a dummy value that let us know something went wrong).  For other situations, where the social contract was not so clear, we had functions like getRegressionResultsForData(), which did some functions to get the data, then called getRegressionResults() on it.

In summary, you should never chain in a situation where a future developer could be mislead by skimming over a function (instead of diving into all sub-functions to look for chains).

Title: When, if ever, should I daisy chain functions?

Body:
In a program divided up into many functions by which it is intended that they execute themselves one after another, when (if ever) is it preferred to:

A) Execute the functions one after another in main()?

or

B) Execute one function in main(), and have that function daisy chain to the rest of the functions that need to be executed?

To illustrate this

Program FlowChart:

Start -> Make foo -> Do bar? -> True -> Say Goodbye -> End

A:

```<code>void makeFoo() {
    [...]
    return;
}
bool doBar() {
    bool bar;
    [...]
    return bar;
}
void sayGoodbye() {
    [...]
    return;
}
int main {
    makeFoo();
    if (doBar()) {
        sayGoodbye();
    }
    return 0;
}
</code>```

B: (Daisy Chain)

```<code>void makeFoo() {
    [...]
    doBar();
    return;
}
void doBar() {
    bool bar;
    [...]
    if (bar) {
        sayGoodbye();
    }
    return;
}
void sayGoodbye() {
    [...]
    return;
}
int main {
    makeFoo();
    return 0;
}
</code>```

Body:
Daisy chain when it is clear to the next developer why you did it that way.

"Code is read more often than it is written." -Guido von Rossum, PEP 008

There is no one answer to this, but I can give you a good rule of thumb: If the name of the function implies that its job is to do one function and call another, then it is safe to chain them.

There are times where two functionalities do really need to chain.  Consider the classic example of error handling

result = doSomething();
if (result == badValue)
    haltAndCatchFire();

If this pattern shows up all the time, the next developer is going to get sore reading it over and over.  Worse, they may get lazy or forget, causing unexpected results.  However, haltAndCatchFire on its own is a pretty useful function to have, so we don't want to bury that functionality into doSomething, just to never see it again.  As a solution:

doSomethingOrHaltAndCatchFire();

Its long, but now it is very clear that you intend to daisy chain.  A developer who does not want to follow you into doSomething can generally assume that you'll call haltAndCatchFire if anything goes wrong, so you have successfully transmitted information to the next developer.  They can keep reading main() without having to dodge and weave through multiple functions.

Your naming choice is up to you, as long as it is clear.  As an example, on one suite of software I developed, there was a pattern:

int getValue();
int tryGetValue();

It was understood (social contract) that getValue() should call exception handling functions if something goes wrong.  TryGetValue should just return (often returning a dummy value that let us know something went wrong).  For other situations, where the social contract was not so clear, we had functions like getRegressionResultsForData(), which did some functions to get the data, then called getRegressionResults() on it.

In summary, you should never chain in a situation where a future developer could be mislead by skimming over a function (instead of diving into all sub-functions to look for chains).


问:
RESTful Backend - How coupled should my back end and front end be?
I'm creating a web application with a front end client written in angular as well as a back end that I'm writing in Django (there are reasons I picked the frameworks but they are irrelevant to my question).

I have my front end planned out down to every page that will be available. I currently am only going to implement the angular cient but in the future I plan on implementing a native android and iOS app for learning purposes.

My question is how coupled should my back end design be with my front end client?

Should I design my endpoints on a per view basis?
This seems like back end will need work when I create another client.

Or should my endpoints be more focused around exposing CRUD functionality for my models?
This seems like it would leave room for creativity and make the back end more flexible.

These are a few of the questions I have been asking myself and I provided them to add a little more scope to my question.

Even if I went with the crud approach it seems like I will still be implementing specialized endpoints for handling common application features.

Thanks in advance.

答:
You should design your backend around the resources you are exposing from the backend.

These do not have to match up exactly to your model (the exposed resources and the internal model are two separate things), but often you will have a lot of overlap. For example you might have a "user" model object and a "user" resource exposed by the server.

A "resource" is an abstract concept, but it is important to have in your head what resources your server exposes to clients.

Once you have figured that out writing the client should be a doddle since the client simply requests the resources and does something with them.

To give an example of where resources and domain model don't necessary completely over lap imagine a server that exposed a "student" resource to clients, but in the domain model there were actually 10 different objects that went into creating that resource (none of them called 'student')

So the resource url for a student looked like "/students/[id]" but when that was accessed the server created 10 different models, from Person to Grade, to School in order to build that single resource.

A lot of web frameworks, such as Django, map resources very closely to domain model which can make things easier (eg /students/[id] maps directly to a Student object in the model), but it is important to remember that this is not a requirement or sometimes not even a good idea.


问:
CSS practices: negative positioning
I'm somewhat of a novice to CSS.

Anyway, I noticed that an extremely common method used in CSS is to have negative or off-screen positioning, whether it be to hide text or preload images or what have you.

Even on SE sites, like StackOverflow and this website, have

```<code>#hlogo a { text-indent: -999999em }
</code>```

set in their CSS.

So I guess I have a few questions.

is this valid CSS? or is it just a "hack"?

are there downsides to doing things this way?

why is this so common? aren't there better ways to hide content?

答:
It's a hack used to hide text while using images as backgrounds, mostly seen into practice with site branding. The modern-day websites do it the better way by simply using  to display logos.

It is valid CSS.

The only downside is that the text can't be visible.

Don't really know why this is common, but there are better techniques to hide text if you can ignore older versions of web browsers.

ContentLicense: CC BY-SA 2.5

Title: CSS practices: negative positioning

Body:
It's a hack used to hide text while using images as backgrounds, mostly seen into practice with site branding. The modern-day websites do it the better way by simply using <img> to display logos.

It is valid CSS.

The only downside is that the text can't be visible.

Don't really know why this is common, but there are better techniques to hide text if you can ignore older versions of web browsers.


问:
How to design a RESTful API with good performance
When designing RESTful APIs, one of the rules is: "URI designates exactly one resource" , but in the real world we also like good performance and one thing to kill performance is the N+1 problem.

So how exactly are we supposed to avoid the N+1 problem without making more than one URI for the same resource /api/foos/?page=1 or /api/foo/1 where /api/foos/ returns a list of foos in order to get decent performance.

答: No one said you can't make a URI for /api/foos/?page=1. A container is not the same as the things it contains; a list of foos is a different resource from the individual foos.


问:
Version control for independent developers?
Do you think it's worth it to use version control if you are an independent developer, and if so, why? Do you keep the repository on your own computer, or elsewhere, where it can serve as a backup?</p>

答: Absolutely use source control. Then set up a build server and automate your build and testing processes. Trigger builds from your source commits of your central repo. I have been working by myself for three years in this way and it's wonderful.</p>


问:
How can I condense a case class with ~20 constructor arguments into 5 or 6 arguments in Scala?
Let's say I have a case class with ~20 constructor arguments? This is obviously very clunky to type. What would be the best way to condense these arguments into maybe 5 or 6 arguments? There are some arguments that are related to each other enough that I could see doing:

```<code>case class myClass(myStorageContainer, myOtherStorageContainer...)
</code>```

instead of

```<code>case class myClass(arg0...arg19)
</code>```

Since this case class with be stored in a large list of case classes of this type I'm unsure if the overhead would be significant having to initialize so many objects to build the constructor arguments out.

答:
Of the things you should be worried about as a programmer, initialization overhead is way, way down on the list.  Your suggested grouping is a minimal first step.

The next step is to reconsider if you actually need to keep all that data together in one case class.  You almost never do, and it usually hurts you to create that large of a coupling.

One thing that often works is instead of storing one massive list of myClasses, store individual lists of myStorageContainers or even args.  Then re-associate them on the fly as needed using zip or map or some such.

This feels wrong for programmers trained in imperative languages, whose instinct is to protect their data from other people mutating it, and whose architectural style has developed accordingly.

Immutability means you don't need to store data in the same container in order to maintain invariant relationships between them.  If I have an immutable List of arg0 and another immutable List of arg1 that are created together, then I know that the nth element of the first list always goes with the nth element of the second list.  Likewise for objects stored in separate immutable maps indexed using the same key.  They don't have to be physically in the same data structure.

Give it a try and see.  You will probably find your modularity go way up when functions are no longer coupled to a giant case class.


问:
How to make scalable modules in a div element
I'm interested in creating web modules that are encapsulated by a div element in a manner that, by simply resizing the div, everything in that div scales to the dimensions of that div proportionately (fonts, sub-divs, etc.).

A couple of weeks ago, I made this form that scales pretty well as you resize the page. I was able to achieve this by sizing things with the CSS3 viewport relative sizing units.

These viewport units work great if your module is the size of the entire viewport (the size of the whole page), but these same units don't work if your intended "viewport" is going to be just a div that is only one part of an entire web page and a div you intend to reuse in multiple pages with total different "surroundings".

Conceptually, the idea is to be able to create reusable modules that can be placed anywhere inside of any webpage, and by simply setting the modules div container size, all contents scale proportionately based on the size of the div.

I want to create modules that can be consumed by any webmaster, and all the webmaster has to do is set the height, width and location of the module, and the module scales perfectly to the webmaster's desired dimensions.

Any advice toward this concept would be appreciated.

答:
François REMY wrote:

Hi Lonnie,

I think your pain is valid, and important.

You'll be happy to learn that there are currently proposals for "module-like" local viewports similar to what you want. An example (taken at random, of course) would be my own proposal http://fremycompany.com/TR/2012/ED-css-viewport/ (which should probably mention that the "vh" and "vw" units will map to the width/height of the element which is set as a local viewport, for its descendants) but some better articles were also written by people at Google last year about why we want something along those lines.

The issue at this point is also somewhat debated in the Responsive community group in the form of ":min-width/:max-width" for which I believe the requirement and problems to solve are close if not identical to the ones faced by an implementation which would satisfy your needs.

I think it's great you provided a reminder to the css group webdevelopers care enough about the problem to find their way up to here to voice their opinion, this is valuable, so thanks!

Best regards,
François

Above is a reply received from the w3.org mailing list, to my message below:

In CSS, there needs to be a way to specify the specific element you want to base your relative sizing units off of. Relative sizing units shouldn't necessarily be based on a parent element's size, or the page's size, or the viewport. A web module may have numerous child-elements of various depths, and the element you want to base relative sizing units off of might not be an immediate ancestor!

For example, please take a look at the question I posted here:
How to make scalable modules in a div element

I like how the viewport units allow you to scale the contents of a page. I
made this page, and am happy that even the fonts are scaling well on it:
http://www.lonniebest.com/emailform/

However, my ultimate goal is to be able to create composite web-modules (that are encapsulated by one div element, for example) that can be placed onto any web-page in a manner that a webmaster can scale that element's contents just by simply setting the divs height and width. To do this, I really need relative sizing units to be base on a particular element -- the one that encapsulates
my entire web-module.

To some degree, this can be achieve with % units, but not for font-size! I have not found a relative font-size unit that can be based on the size of a parent element. If a webmaster put my self-made module onto his page, my font-sizes will be based on this size of his page, and NOT base on the size he decided to set my module.

Viewport units work great if you web-module is the size of the viewport; resizing the window makes even fonts re-size proportionately.

The web is getting very close to offering the same scalable modules of non-web technologies such as QML and WPF.

If CSS could offer a way for a webmaster to "specify a particular element that relative sizing units are to be base on", this seems perfect.

Again, a web module may have numerous child-elements of various depths, and the element you want to base relative sizing units off of might not be an immediate ancestor and it might not be the page as whole. For a web module, you want relative size of fonts and everything else to be based on that module's size (not the page as a whole).

CSS should be so flexible, that I can create an independent module and you can put it onto your page, and by simple setting my modules height, width, and location: everything contained in that module scales proportionately to your environment. If you make the size of my module super small, the fonts should be super small, not based on the page as a whole.

Lonnie Best

ContentLicense: CC BY-SA 4.0


答:
Not daisy-chaining is almost always preferred.  Look at your example, and imagine a future maintainer reading this code to fix a bug, without the benefit of the flow chart.

It's tough to tell from dummy example function names, but in a real program, he can read the main function to reconstruct the overall flow and tell where to look next by the names of the functions.  In the daisy-chained version, he would have to look into every single function, which might span several files.  Likewise, in the daisy-chained version, changing one step might cause a ripple effect through the rest of the code.

However, cramming all the steps into the main function isn't necessarily the answer either.  You want to create functions where everything you read is on the same level of abstraction.  Perhaps makeFoo has several substeps.  It's okay to leave those there and just return the sub-result back to main.


问:
IoC invalidation
I have a bunch of services that get registered as singletons by my IoC container on startup, all of these services have a constructor which takes in a connection string which is used by the underlying storage provider.

This has been fine given the connection string was static and never changed during a session, however, I now need to implement the ability for users to change the connection string at runtime (e.g. they can choose to point to a local/cloud DB).

Ultimately, what this means is I need to somehow invalidate all my services in the IoC container and as far as I could see my chosen IoC container doesn't appear to provide a means of doing this, so it's down to me to come up with a practical solution.

Now there are many ways I could do this but I am looking for feedback, suggestions (from experience if possible) on what would be considered the optimal solution. Here is a simplified service

```<code>public class Service
{
    public Service (string connectionString)
    {
        this.ConnectionString = connectionString;
    }

    // marked as protected as derived services may need access to them
    protected string ConnectionString { get; set; }
    ...
}
</code>```

And here is how it is currently registered

```<code>public static void StartUp(IAppSettings appSettings)
{
    container.Register<IService, Service> (new Service(appSettings.ConnectionString));
    ...
}
</code>```

The simplest solution, which I personally don't like, is simply to have all my services take a reference to IAppSettings rather than ConnectionString and use a read-only property e.g.

```<code>protected string ConnectionString { get { return appSettings.ConnectionString; } }
</code>```

However, given all that the services need from IAppSettings is the connection string this just seems wrong from a modelling point of view. Keeping with this approach, but improving on it slightly would be to introduce a new interface which exposes only the information needed from IAppSettings e.g.

```<code>public interface IDbSettings
{
    string ConnectionString { get; set; }
}

public class AppSettings : IAppSettings, IDbSettings
{
    ...
}
...
container.Register<IService, Service> (new Service(appSettings as IDbSettings));
</code>```

I say slightly because ultimately I still have the same problem (services are still referencing a large object for one simple property).

The type of approach I would like, and what I feel would be best, would be to extend the current IoC container to introduce an Invalidate method whereby I can simply set the internal instance to null and have it re-initialized when resolved. I see this looking something like

```<code>appSettings.ConnectionString = "database=db1";
container.Register<IService, Service>(new Service(appSettings.ConnectionString));
...
var svc = container.Resolve<IService>(); // connects to db1
appSettings.ConnectionString = "database=db2";
...
var svc = container.Resolve<IService>(); // still connects to db1
container.Invalidate<IService>();
var svc = container.Resolve<IService>(); // connects to db2
</code>```

For me this gives all round benefits

You control exactly when you want the changes to take affect

It keeps with the Singleton pattern

It means the only thing that changes is the IoC container

I would be interested in everyones thoughts, critiques etc.

答:
Is the construction of your services expensive? What about tear down?

If your objects are singletons and responsible for building and holding a connection to the database for their lifetime, how do you handle transactions or concurrent requests to the database?

I think a better solution would be to put your database connectivity into a transient life IDBService and give your services a transient life with a dependency on the IDBService.

Title: IoC invalidation


答:
It depends. Usually you shouldn't daisy-chain functions, unless the daisy-chain is a implementation detail, not part of the main process at all. That's why we have main functions after all. If someone else (including you in 6 months) has to read that code, it's much easier to find a function that describes the algorithm of a program, isolated into functions that implement the steps of that algorithm. Especially in scripts, you want to show the procedure as clearly as you can, as to write self-documenting code.

I usually start by writing a central function with a lot of invalid placeholder statements, like this:

```<code>def foo_the_bar(xkcd):
    unfooed_bars = discover_bars(xkcd)
    foo = load_foo_from_orbital_cannon()
    return map(foo, unfooed_bars)
</code>```

Then go into implementing those functions, until there's a complete program. You get to isolate logic, and make functions agnostic of what they will be used for.

To get what a program made this way does, you barely have to dive into the inner functions (as long as they are documented and named properly).

Daisy chaining produces some of these bad effects:

functions that do their thing, then adapt their result to the next daisy link

functions that expect a specific order of things to have happened to the data

human stack overflows

The last point is key: Humans have a context stack, and in some senses it's much more limited than a computer's, because computers don't need to make sense of the whole combination of procedures, they only care about the current state and their instructions.

Every time a human reads your daisy code, he has to add a new context manager to the brain stack. This operation takes a while, and then when you need to refer to the upper contexts, you have to pop all the way to the correct context, to then return to the place you were.

In short: If you're going to daisy chain, you might scrap using functions at all, it might even be more readable.

Body:
It depends. Usually you shouldn't daisy-chain functions, unless the daisy-chain is a implementation detail, not part of the main process at all. That's why we have main functions after all. If someone else (including you in 6 months) has to read that code, it's much easier to find a function that describes the algorithm of a program, isolated into functions that implement the steps of that algorithm. Especially in scripts, you want to show the procedure as clearly as you can, as to write self-documenting code.

I usually start by writing a central function with a lot of invalid placeholder statements, like this:

def foo_the_bar(xkcd):
    unfooed_bars = discover_bars(xkcd)
    foo = load_foo_from_orbital_cannon()
    return map(foo, unfooed_bars)

Then go into implementing those functions, until there's a complete program. You get to isolate logic, and make functions agnostic of what they will be used for.

To get what a program made this way does, you barely have to dive into the inner functions (as long as they are documented and named properly).

Daisy chaining produces some of these bad effects:

functions that do their thing, then adapt their result to the next daisy link

functions that expect a specific order of things to have happened to the data

human stack overflows

The last point is key: Humans have a context stack, and in some senses it's much more limited than a computer's, because computers don't need to make sense of the whole combination of procedures, they only care about the current state and their instructions.

Every time a human reads your daisy code, he has to add a new context manager to the brain stack. This operation takes a while, and then when you need to refer to the upper contexts, you have to pop all the way to the correct context, to then return to the place you were.

In short: If you're going to daisy chain, you might scrap using functions at all, it might even be more readable.


问:
"Use map instead of class to represent data" -Rich Hickey
In this video by Rich Hickey, the Clojure creator, he advises to use map to represent data instead of using a class to represent it, as done in Java. I don't understand how it can be better, since how can the API user know what the input keys are if they are simply represented as maps.

Example:

```<code>PersonAPI {
    Person addPerson(Person obj);
    Map<String, Object> addPerson(Map<String, Object> personMap);
}
</code>```

In the second function, how does the API user know what the needed inputs are for creating a person?

答:
That's an excellent talk by someone who really knows what he's talking about.  I recommend readers watch the entire thing.  It's only 36 minutes long.

One of his main points is that simplicity opens opportunities for change later on.  Choosing a class to represent a Person provides the immediate benefit of creating a statically-verifiable API, as you pointed out, but that comes with the cost of limiting opportunities or increasing costs for change and reuse later on.

His point is that using the class might be a reasonable choice, but it should be a conscious choice that comes with full awareness of its cost, and programmers traditionally do a very poor job of noticing those costs, let alone taking them into consideration.  That choice should be reevaluated as your requirements grow.

The following are some code changes (one or two of which were mentioned in the talk) that are potentially simpler using a list of maps compared to using a list of Person objects:

Sending a person to a REST server.  (A function created to put a Map of primitives into a transmittable format is highly reusable and might even be provided in a library.  A Person object is likely to need custom code to accomplish the same job).

Automatically construct a list of people from a relational database query.  (Again, one generic and highly-reusable function).

Automatically generate a form to display and edit a person.

Use common functions to work with person data that is highly non-homogeneous, like a student versus an employee.

Get a list of all persons who reside in a certain zip code.

Reuse that code to get a list of all businesses in a certain zip code.

Add a customer-specific field to a person without affecting other clients.

We solve these kinds of problems all the time, and have patterns and tools for them, but rarely stop to think about if choosing a simpler, more flexible data representation in the beginning would have made our job easier.


答:
The API for a map has two levels.

The API for maps.

The conventions of the application.

The API can be described in the map by convention. For example the pair :api api-validate can be placed in the map or :api-foo validate-foo could be the convention. The map can even store api api-documentation-link.

Using conventions lets the programmer create a domain specific language that standardizes access across  "types" implemented as maps.  Using (keys map) allows for determining properties at runtime.

There's nothing magical about maps and there's nothing magical about objects. It's all dispatch.

Title: "Use map instead of class to represent data" -Rich Hickey

Body:
In this video by Rich Hickey, the Clojure creator, he advises to use map to represent data instead of using a class to represent it, as done in Java. I don't understand how it can be better, since how can the API user know what the input keys are if they are simply represented as maps.

Example:

```<code>PersonAPI {
    Person addPerson(Person obj);
    Map<String, Object> addPerson(Map<String, Object> personMap);
}
</code>```

In the second function, how does the API user know what the needed inputs are for creating a person?


答:
If the data has little or no behavior, with flexible content that is likely to change, use a Map.  IMO, a typical "javabean" or "Data Object" that consists of an Anemic Domain Model with N fields, N setters and N getters, is a waste of time.  Don't try to impress others with your glorified struct by wrapping it in a fancy smancy class.  Be honest, make your intentions clear, and use a Map.  (Or, if it makes any sense to your domain, a JSON or XML object)

If the data has significant actual behavior, a.k.a methods (Tell, Don't Ask), then use a class.  And pat yourself on the back for using real Object Oriented programming :-).

If the data has a lot of essential validation behavior and required fields, use a class.

If the data has a moderate amount of validation behavior, that's borderline.

If the data fires property change events, that is actually easier and far less tedious with a Map.  Just write a little subclass.

One main drawback of using a Map is that the user has to cast the values to Strings, ints, Foos, etc.  If this is highly annoying and error-prone, consider a class.  Or consider a helper class that wraps the Map with the relevant getters.


答:
I cannot comment yet, but these generics are also valid:

```<code>private event Action SomeEvent1;
private event Action<int> SomeEvent2;
private event Func<int, int, int> SomeEvent3;
</code>```

This provides an ambiguously un-descriptive template if auto-generated:

```<code>int CLASSNAME_SomeEvent3(int arg1, int arg2) //arg what? argh!!
{
}
</code>```

Body:
I cannot comment yet, but these generics are also valid:

private event Action SomeEvent1;
private event Action<int> SomeEvent2;
private event Func<int, int, int> SomeEvent3;

This provides an ambiguously un-descriptive template if auto-generated:

int CLASSNAME_SomeEvent3(int arg1, int arg2) //arg what? argh!!
{
}


问:
Is it good to split big repository into smaller ones to have separate history/issue etc or keep it big?
We are currently porting our huge svn repo to git and we are thinking to export subdirectories of repository, each one containing source code of independent binaries, documentation or robot tests, into separate git projects.

One of those is a library that is currently being developed and all of the binaries depend on it.

All of those directories/binaries/docs etc are currently developed.

Should we separate all of those into separate git repos or add submodules or keep it as it is one huge repo?

Catalog structure:

```<code>/trunk/src/
    binary1/
    binary2/
    binary3/
    binary4/
    binary5/
    library/
    TA_tests/
    docs/
    scripts/
</code>```

答: I think that would be a great idea because it will keep things nice and neat for the humans that would have to read it. I usually use sub-directories with my code to make it more human readable. Not using human readable code gives me a headache and makes looking for things very hard. The best thing you can do is put the main executable file in the home directory and break everything else up. Good luck!</p>


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答: The biggest myth is that it's easy.</p>

Body: The biggest myth is that it's easy.


问:
operator"" in modern C++
I took an example I found on-line whereby a constexpr of the form _binary could be evaluated at compile time as an unsigned long long and then I tried to generalize it for any base from 2 to 36.  For instance, 17b1234_baseChange would be evaluated from base 17 as ((1*17 +2)*17 + 3)*17 + 4 = 5624.

I realize this is kind of a contrived example but I was wondering what the limits are for operator"".  Is seems like the compiler when parser is creating separate tokens for numbers and letters.  I was curious if this was a bug or expected behavior.  (In addition to 'b', I have tried other separators with no luck.)
Thanks for your insight.

Command line within http://coliru.stacked-crooked.com/:
g++-4.9 -std=c++14 -O3 -Wall -Wextra -pedantic -pthread -pedantic-errors main.cpp -lm  && ./a.out

Code:

```<code>#include <iostream>

const char Delimiter = 'b';
typedef unsigned long long ULL;

/// Extract one "digit" from a digit string and then recurse.
template<unsigned short NumericBase, char Head, char... Rest>
struct baseChange_helper
{
  constexpr ULL operator()(ULL result) const;
};

/// Teminate recursion when interpreting a numeric string.
template<unsigned short NumericBase, char Head> struct
baseChange_helper<NumericBase, Head>
{
   constexpr ULL operator()(ULL result) const;
};

template<unsigned short NumericBase, char Head, char... Rest>
constexpr ULL baseChange_helper<NumericBase, Head, Rest...>::operator()
(ULL result) const
{
   static_assert(   (Head >= '0' && (Head <= '0' + std::min(NumericBase-1, 9)))
                 || (NumericBase > 10 && (Head >= 'A' && Head <= 'A' +
                     std::min(NumericBase-10, 25)))
                 , "not a valid number in this base");
    return baseChange_helper<Rest...>{}(result = result * (NumericBase -1)
                         + ((Head > 'A') ? (10 + Head - 'A') : (Head - '0')));
}

template<unsigned short NumericBase, char Head>
constexpr ULL
baseChange_helper<NumericBase, Head>::operator()(ULL result) const
{
    static_assert(   (Head >= '0' && (Head <= '0' + std::min(NumericBase-1, 9)))
                 || (NumericBase > 10 && (Head >= 'A' &&
                     Head <= 'A' + std::min(NumericBase-10, 25)))
                 , "not a valid number in this base");
   return  result * (NumericBase -1)  +
           ((Head > 'A') ? (10 + Head - 'A') : (Head - '0'));
}

template<unsigned short NumericBase, char Head, char... Rest> struct
baseChange_parser
{
   constexpr ULL operator()() const;
};
template<unsigned short NumericBase, char Head, char... Rest>
constexpr ULL baseChange_parser<NumericBase, Head, Rest...>::operator()()
const
{
   static_assert( (Head == Delimiter && NumericBase > 1 && NumericBase < 36) ||
                  (Head >= '0' && Head <= '9'),
                  "not a valid base");
   return ( Head == Delimiter ? baseChange_helper<NumericBase, Rest...>((ULL)0)
                    : baseChange_parser<NumericBase*10 + Head - '0', Rest...>()
          );
}
template<char... Chars> constexpr ULL operator"" _baseChange()
{
   return baseChange_parser<0, Chars...>{}();
}

int main() {
    const ULL v = 17b1234_baseChange;
    std::cout << v << std::endl;
}
</code>```

答:
I don't think this is supposed to work. The system works on the string representations of individual tokens, so because in your example "17b12345_baseChange" the "b" is not an acceptable character for an integer literal (see note below) the token is split at that point, and the base change operation only sees "12345", leaving "17b" behind to generate a syntax error.

I do wonder how this interacts with C++14 digit grouping characters, however - could you get it to understand "17'12345" perhaps?

Note: except in the string "0b" which is only allowed at the start of the literal

Title: operator"" in modern C++


问:
When do you use float and when do you use double
Frequently, in my programming experience, I need to make a decision whether I should use float or double for my real numbers. Sometimes I go for float, sometimes I go for double, but really this feels more subjective. If I would be confronted to defend my decision, I would probably not give sound reasons.

When do you use float and when do you use double? Do you always use double, only when memory constraints are present you go for float? Or you always use float unless the precision requirement requires you to use double? Are there some substantial differences regarding the computational complexity of basic arithmetics between float and double? What are the pros and cons of using float or double? And have you even used long double?

答: The choice of what variable to use between float and double depends on the accuracy of the data required. If an answer is required to have negligible difference from the actual answer, number of decimal places required will be many thus will dictate that double to be in use.Float will chop off some decimal places part thus reducing the accuracy.</p>


问:
Is a guardfile part of the private developers environment or the public OSS project?
Let us say I have an open source project on github. Now I wish to include tools required to develop the project so others can easily contribute. It is hard for me to tell when these tools should be included in the project for others to use and when they are a personal preference and part of my private development environment.

For example, I understand that a vim config file should not be part of the project as it is part of my editor of choice. I also understand that a Gemfile should be part of the repository as it is required to run the project. I have a problem where these two cross.

What about a Guardfile[1]? This file would automatically compiles/refreshes certain parts of the project if a specific command is called from the command line. Some few developers may have an IDE or substitute which already does this, however most would be happy to have a project-specific and tailored Guardfile.

Would adding such a file be alright or does it cross the line of the developers environment?

[1] https://github.com/guard/guard

答:
TL;DR

Canonical build or test files should always be included in the repository. Files that are expected to be customized by each developer should be included in a minimalist way within the repository, often in the form of example files.

Reasons to Include a Baseline Guardfile Verbatim

Files which are required to build or test your code base should be included in the repository. A Guardfile that contains customizations necessary to run your test suite properly, such as RSpec-related arguments, might therefore make sense as an integral part of the repository. However, the Guardfile should not contain personal preferences such as screen clearing or other per-developer customizations.

On many projects, a standard Guardfile may be a perfectly reasonable thing to commit, provided that all of the team members expect to use the same configuration. This will ensure that things "just work" after cloning, but at the cost of enforcing a vanilla configuration across all developer workstations.

Reasons to Include a Sample Guardfile for Customization

On projects where the customization of the Guardfile isn't needed, it makes sense to commit the Guardfile directly. However, on teams or projects where the Guardfile in use may vary between developers, it's often better to commit an example such as Guardfile.example that developers can then copy to Guardfile before editing it, ensuring that individual customizations aren't committed upstream.

Note that this approach also requires that the filename for customizations be added to the project's .gitignore file, or the equivalent for your SCM of choice. You will generally want changes to Guardfile.example to be committed for future users, but will not want each developer's customized Guardfile to be committed if they do something common like git add . when committing new work.

The downside of the example-file approach is that it requires a manual step by each developer to properly configure the tool-chain before first use. This adds to the cognitive load of bootstrapping the project, and can easily be forgotten or overlooked when cloning a project. Even if the step is documented in your readme, or your project includes some kind of setup script that includes a line like cp Guardfile{.example,}, having to rename or configure tool-specific configuration files like Guardfile or .rspec before being able to run your test suite properly the first time may violate the principle of least surprise for new team members.