问:
Should accessible members of an internal class be internal too?
I'm designing a set of APIs for some applications I'm working on.  I want to keep the code style consistent in all the classes I write but I've found that there are a few inconsistencies that I'm introducing and I don't know what the best way to resolve them is.

My example here is specific to C# but this would apply to any language with similar mechanisms.

There are a few classes that I need for implementation purposes that I don't necessarily want to expose in the API so I make them internal whereever needed.

Generally what I would do is design the class as I normally would (e.g., make members public/protected/private where necessary) and change the visibility level of the class itself to internal.  So I might have a few classes that look like this:

internal interface IMyItem
{
    ItemSet AddTo(ItemSet set);
}

internal class _SmallItem : IMyItem
{
    private readonly /* parameters */;
    public _SmallItem(/* small item parameters */) { /* ... */ }

    public ItemSet AddTo(ItemSet set) { /* ... */ }
}

internal abstract class _CompositeItem: IMyItem
{
    private readonly /* parameters */;
    public _CompositeItem(/* composite item parameters */) { /* ... */ }

    public abstract object UsefulInformation { get; }
    protected void HelperMethod(/* parameters */) { /* ... */ }
}

internal class _BigItem : _CompositeItem
{
    private readonly /* parameters */;
    public _BigItem(/* big item parameters */) { /* ... */ }

    public override object UsefulInformation
    {
        get { /* ... */ }
    }

    public ItemSet AddTo(ItemSet set) { /* ... */ }
}
```

<p>In another generated class (part of a parser/scanner), there is a structure that contains fields for all possible values it can represent.  The class generated is <code>internal</code> too but I have control over the visibility of the members and decided to make them <code>internal</code> as well.</p>

<pre class="lang-cs prettyprint-override"><code>internal partial struct ValueType
{
    internal string               String;
    internal ItemSet              ItemSet;
    internal IMyItem              MyItem;
}

internal class TokenValue
{
    internal static int EQ(ItemSetScanner scanner) { /* ... */ }
    internal static int NAME(ItemSetScanner scanner, string value) { /* ... */ }
    internal static int VALUE(ItemSetScanner scanner, string value) { /* ... */ }
    //...
}
</code>```

To me, this feels odd because the first set of classes, I didn't necessarily have to make some members public, they very well could have been made internal.  internal members of an internal type can only be accessed internally anyway so why make them public?  I just don't like the idea that the way I write my classes has to change drastically (i.e., change all uses of public to internal) just because the class is internal.

Any thoughts on what I should do here?

It makes sense to me that I might want to make some members of a class declared public, internal.  But it's less clear to me when the class is declared internal.

答:
just make sure that in your given language there is no what I'll call "side channel" through which consumers  of your api could access a public member of an internal class, because if there is, and they find it and use it, that part of your code is "as good as" public api from  then on. That means they scream if you change it and you get stuck supporting it.

In Java one example of a side channel is reflection. Devs can and have used it to gain access to members which the api author never intended they should know about.

OwnerDisplayName: Jeff Mercado


问:
Python methods vs builtin functions
Python widely uses built-ins (or module function) and not class methods.

So

len([]) instead of [].length()

filter(f, []) instead of [].filter(f)

str(2) instead of 2.to_str

same for map, foreach etc

These prevent you from doing nice chaining which is possible in other languages like Ruby or Scala:

(sorry very artificial example)

```<code>my_list.map(f).filter(g).length()
</code>```

In Python you would need to either split into several lines:

```<code>list_of_something_else = map(f, my_list)
list_of_something_else_without_blah = filter(g, list_of_something_else)
length = len(list_of_something_else_without_blah)
</code>```

In a single expression it doesn't look readable:

```<code>len(filter(g, map(f, my_list))
</code>```

Is it considered to be not-Pythonic to chain methods?

Or do people usually extend classes with a dozen of helper functions to make it easier?

答:
The Python functions are universally applicable; anything that has a __len__ method will work for len(), anything that's iterable will work for map(), etc.

Another reason for len() to be a function is that it guarantees that the name is now the standard way of determining the length of any container; add-on types will have to implement __len__ to be compatible; if Python picked list.length() instead, other types could've implemented foo.get_length() or bar.len() or anything. Python followed the Principle of Least Astonishment instead here.

And Guido van Rossum found len() to be more readable (I agree).

And no, most of the Python stdlib doesn't support chaining; this can lead to overly-long lines that aren't very readable either. Instead, Python's syntax is generally powerful enough that you don't need much chaining.

Your last expression would be better rewritten as:

```<code>sum(1 for i in my_list if g(f(i)))
</code>```

as that'd save you having to create an intermediary list just to get the count of elements that were left after filtering.

ContentLicense: CC BY-SA 3.0

Title: Python methods vs builtin functions

Body:
The Python functions are universally applicable; anything that has a __len__ method will work for len(), anything that's iterable will work for map(), etc.

Another reason for len() to be a function is that it guarantees that the name is now the standard way of determining the length of any container; add-on types will have to implement __len__ to be compatible; if Python picked list.length() instead, other types could've implemented foo.get_length() or bar.len() or anything. Python followed the Principle of Least Astonishment instead here.

And Guido van Rossum found len() to be more readable (I agree).

And no, most of the Python stdlib doesn't support chaining; this can lead to overly-long lines that aren't very readable either. Instead, Python's syntax is generally powerful enough that you don't need much chaining.

Your last expression would be better rewritten as:

sum(1 for i in my_list if g(f(i)))

as that'd save you having to create an intermediary list just to get the count of elements that were left after filtering.


答: What you really want is an infix function for chaining like Haskell's $. The sigil need not be $, it could be something more evocative like |> or ->. len, filter, etc are all free functions, so giving them object syntax just for the sake of chaining feels like a kludge to me.

Title: Python methods vs builtin functions

Body:
Python widely uses built-ins (or module function) and not class methods.

So

len([]) instead of [].length()

filter(f, []) instead of [].filter(f)

str(2) instead of 2.to_str

same for map, foreach etc

These prevent you from doing nice chaining which is possible in other languages like Ruby or Scala:

(sorry very artificial example)

```<code>my_list.map(f).filter(g).length()
</code>```

In Python you would need to either split into several lines:

```<code>list_of_something_else = map(f, my_list)
list_of_something_else_without_blah = filter(g, list_of_something_else)
length = len(list_of_something_else_without_blah)
</code>```

In a single expression it doesn't look readable:

```<code>len(filter(g, map(f, my_list))
</code>```

Is it considered to be not-Pythonic to chain methods?

Or do people usually extend classes with a dozen of helper functions to make it easier?


答:
It's worth noting that Python isn't without chain functions, or class methods. For example, imagine a JSON-esque dict that may contain dicts as well:

```<code>persondict = {"name": "Joe Foo",
          "DOB": "06/07/75",
          "address": {"street_addr": "123 Some Street",
                      "city": "Anywhere",
                      "state": "MA",
                      "zip": 12345}
          "children": None}
</code>```

Dicts do have a get method which returns the value for a named key, as well as an optional argument for a dict with no such key. So in the above situation, if we were to assume that the children were also going to be similar dicts, one could write a function as follows:

```<code>def get_person_states(jsonlikedb):
    """Gets a list of the states the passed persondicts live in."""
    results = []
    for persondict in jsonlikedb:
        addr = persondict.get('address', {}).get('state')
        if addr is not None:
            results.append(addr)
    return results
</code>```

This would search each persondict for the 'address' key, and then search the return value for 'state' and return that. If the first get() fails to find an 'address' key, it will return an empty dict; this allows the second call to get() to gracefully bail if the persondict has no address.

Having said that, what's considered 'Pythonic' does not necessarily equate to 'what follows the most conventions' but rather 'what follows the most Python-like convention'. To that end, principles like duck typing and eafp take precedence over things which may work in other languages as a matter of tradition. As an example of both:

```<code>def cut_in_half(someobj):
    try:
        halfway = len(someobj) / 2
        return someobj[:halfway], someobj[halfway:]
    except TypeError:
        print "This object is indivisible!!"
        return someobj
</code>```

In this way the function can never try to split an object that does not have a __len__ method.

As long as it's being discussed -- while it is not necessarily Pythonic, one is well able to call __len__ directly, so if you're pining for doing it a different way, it can technically be done in this direct fashion:

```<code>print my_obj_with_length.__len__()
</code>```

…however, it's not particularly Pythonic to do so.

Title: Python methods vs builtin functions

Body:
It's worth noting that Python isn't without chain functions, or class methods. For example, imagine a JSON-esque dict that may contain dicts as well:

persondict = {"name": "Joe Foo",
          "DOB": "06/07/75",
          "address": {"street_addr": "123 Some Street",
                      "city": "Anywhere",
                      "state": "MA",
                      "zip": 12345}
          "children": None}

Dicts do have a get method which returns the value for a named key, as well as an optional argument for a dict with no such key. So in the above situation, if we were to assume that the children were also going to be similar dicts, one could write a function as follows:

def get_person_states(jsonlikedb):
    """Gets a list of the states the passed persondicts live in."""
    results = []
    for persondict in jsonlikedb:
        addr = persondict.get('address', {}).get('state')
        if addr is not None:
            results.append(addr)
    return results

This would search each persondict for the 'address' key, and then search the return value for 'state' and return that. If the first get() fails to find an 'address' key, it will return an empty dict; this allows the second call to get() to gracefully bail if the persondict has no address.

Having said that, what's considered 'Pythonic' does not necessarily equate to 'what follows the most conventions' but rather 'what follows the most Python-like convention'. To that end, principles like duck typing and eafp take precedence over things which may work in other languages as a matter of tradition. As an example of both:

def cut_in_half(someobj):
    try:
        halfway = len(someobj) / 2
        return someobj[:halfway], someobj[halfway:]
    except TypeError:
        print "This object is indivisible!!"
        return someobj

In this way the function can never try to split an object that does not have a __len__ method.

As long as it's being discussed -- while it is not necessarily Pythonic, one is well able to call __len__ directly, so if you're pining for doing it a different way, it can technically be done in this direct fashion:

print my_obj_with_length.__len__()

…however, it's not particularly Pythonic to do so.


问:
When/Where to create/assign event handlers to its elements
Lets say I have the following code

```<code>// JS

$(function(){
        $('[data-mc=logout]').click(function(){
                if (!confirm(myconfig.msg['asklogout'])) {
                    return false;
                }
        });

        $('[data-mc=ajax]').click(function(){
                var target=$(this).data('target'); //retrieve data-target of the clicked tag
                return false;
        });
});
</code>```

which target some HTML elements

```<code>//  HTML

Logout
Start page
</code>```

Am I right when I say that this code needs to be called on every
full page load?

a: If so, what if one of the elements doesn't exists on the chosen
page?

b: To avoid errors an "if exist" check is necessary, right?

c: jQuery will do that prior adding the handler?

What if some content gets requested using Ajax and inserted into the
DOM. Then this code needs to be called again, right?

Is this best practice or should the code be split and called per
page load, where only existing element's event handlers gets
attached?

答:
Always, JavaScript and jQuery never does a thing if you don't run it after a full page load.

With jQuery, if no such element(s) exist, nothing happens.

Dynamically added content will not have the handlers that have been applied by previous jQuery calls. I'm not sure exactly what will happen if you run the code again, but you might end up with elements that have multiple handlers attached where you only meant to attach one.

If you are dynamically changing the set of objects that need event handlers you are probably better off putting the event handlers on a static parent element, the document for instance. You can use the jQuery on method to attach an event handler to the document, and pass it a filter string that will cause your handler only to fire when the event happens on an element that match the filter, and with the matched element as this value. The jQuery manual calls this delegated events:

```<code>$(parentElement).on(eventName, filterString, function(){});
</code>```

The only possible downside to delegated events are that event handling may be a bit slower, but I can't think of a realistic example where this is a practical issue.

Body:
Lets say I have the following code

```<code>// JS

$(function(){
        $('[data-mc=logout]').click(function(){
                if (!confirm(myconfig.msg['asklogout'])) {
                    return false;
                }
        });

        $('[data-mc=ajax]').click(function(){
                var target=$(this).data('target'); //retrieve data-target of the clicked tag
                return false;
        });
});
</code>```

which target some HTML elements

```<code>//  HTML

<a class='menulink' data-mc='logout' data-target='main-content-div' href='page/'>Logout</a>
<a class='menulink' data-mc='ajax' data-target='main-content-div' href='page/'>Start page</a>
</code>```

Am I right when I say that this code needs to be called on every
full page load?

a: If so, what if one of the elements doesn't exists on the chosen
page?

b: To avoid errors an "if exist" check is necessary, right?

c: jQuery will do that prior adding the handler?

What if some content gets requested using Ajax and inserted into the
DOM. Then this code needs to be called again, right?

Is this best practice or should the code be split and called per
page load, where only existing element's event handlers gets
attached?

Body:
Always, JavaScript and jQuery never does a thing if you don't run it after a full page load.

With jQuery, if no such element(s) exist, nothing happens.

Dynamically added content will not have the handlers that have been applied by previous jQuery calls. I'm not sure exactly what will happen if you run the code again, but you might end up with elements that have multiple handlers attached where you only meant to attach one.

If you are dynamically changing the set of objects that need event handlers you are probably better off putting the event handlers on a static parent element, the document for instance. You can use the jQuery on method to attach an event handler to the document, and pass it a filter string that will cause your handler only to fire when the event happens on an element that match the filter, and with the matched element as this value. The jQuery manual calls this delegated events:

$(parentElement).on(eventName, filterString, function(){});

The only possible downside to delegated events are that event handling may be a bit slower, but I can't think of a realistic example where this is a practical issue.


问:
What are good unit tests to cover the use case of rolling a die?
I'm trying to get to grips with unit testing.

Say we have a die which can has a default number of sides equal to 6 (but can be 4, 5 sided etc.):

```<code>import random
class Die():
    def __init__(self, sides=6):
        self._sides = sides

    def roll(self):
        return random.randint(1, self._sides)
</code>```

Would the following be valid/useful unit tests?

test a roll in the range 1-6 for a 6 sided die

test a roll of 0 for a 6 sided die

test a roll of 7 for a 6 sided die

test a roll in the range 1-3 for a 3 sided die

test a roll of 0 for a 3 sided die

test a roll of 4 for a 3 sided die

I'm just thinking that these are a waste of time as the random module has been around for long enough but then i think if the random module gets updated (say i update my Python version) then at least i'm covered.

Also, do I even need to test other variations of die rolls e.g. the 3 in this case, or is it good to cover another initialized die state?

答:
Martijn's answer is how you'd do it if you really wanted to run a test that demonstrates that you're calling random.randint. However, at the risk of being told "that doesn't answer the question", I feel this shouldn't be unit tested at all. Mocking randint is no longer black box testing - you're specifically showing that certain things are going on in the implementation. Black box testing it isn't even an option - there is no test you can execute that will prove that the result will never be less than 1 or more than 6.

Can you mock randint? Yes, you can. But what are you proving? That you called it with arguments 1 and sides. What does that mean? You're back in square one - at the end of the day you'll end up having to prove - formally or informally - that calling random.randint(1, sides) correctly implements a dice roll.

I'm all for unit testing. They're fantastic sanity checks and expose the presence of bugs. However, they can never prove their absence, and there's things that can't be asserted through testing at all (e.g. that a particular function never throws an exception or always terminates.) In this particular case, I feel there's very little you stand to gain. For behavior that's deterministic, unit tests make sense because you actually know what the answer you're expecting will be.


问:
Is it conventional to raise a NotImplementedError for methods whose implementation is pending, but not planned to be abstract?
I like to raise a NotImplementedError for any method that I want to implement, but where I haven't gotten around to doing it yet.  I might already have a partial implementation, but prepend it with raise NotImplementedError() because I don't like it yet.  On the other hand, I also like to stick to conventions, because this will make it easier for other people to maintain my code, and conventions might exist for a good reason.

However Pythons documentation for NotImplementedError states:

This exception is derived from RuntimeError. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method.

That is a much more specific, formal use case than the one I describe.  Is it a good, conventional style to raise a NotImplementedError simply to indicate that this part of the API is a work in progress?  If not, is there a different standardised way of indicating this?

答:
It's worth noting that, while the Python documentation provides a use case (and probably the canonical one) for this exception, it doesn't specifically exclude its use in other scenarios.

I would consider it appropriate to raise a NotImplementedError exception if you haven't overridden a method in a base class yet (to satisfy the "interface").

A cursory check on Google suggests that people will understand what you mean if you use the exception in this fashion.  There are no side effects or unintended consequences that I know of; the method will simply throw an exception if it is called, and it will throw an exception that is well-understood by everyone.

The documentation for Python 3 reflects this exact usage:

In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method, or while the class is being developed to indicate that the real implementation still needs to be added. [Emphasis added]


问:
Why are good programmers referred to as Ninjas?
How is a Ninja programmer defined? If it is just an experienced developer, then is there really no better way to describe that? Ninja sounds like a childish marketing ploy designed to attract developers with delusions of self-grandeur. Or am I missing something? In particular I want to know what qualities of a Ninja are desired in programmers that makes the comparison valid (besides the coolness factor)?

I did find this article which makes some good comparisons between Ninja characteristics and Agile development. However, I would like to hear from people who have used the word Ninja for hiring purposes and what their motivation was behind it.

Update: There were several good points raised on both sides of the argument. I've tried to summarize these in my blog post. I've chosen JB's answer as the accepted one because it summarizes all the valid reasons for making the comparison.

答:
To my mind there are a few parallels between a Ninja and a good programmer:

Hidden weapons/unorthodox style - If you ever saw the G.I. Joe cartoon from the 1980s you may remember the character of Storm Shadow.  He had a sword and some throwing stars but with just the right sequences of punches and kicks managed to take apart a tank in an episode. In a similar manner, programmers can get called in to do some work that requires them to pull out weapons you may not have thought they had.  This is a kin the "Hacker" point that has been mentioned in a few places.

Honor/respect - Granted that I've seen this more in the Western portrayals of a ninja such as G.I. Joe or Teenage Mutant Ninja Turtles, but there seemed to be this attitude of honoring one's enemy, possibly taken from "Art of War."  Good programmers can respect that there may be better ones out there somewhere.  Humility is also in this in a sense.

Implied mastery - There may be this assumption that all ninjas are masters and thus have really honed their skills to know how to fight well.  Good programmers may have similarly mastered some skills that are quite beneficial in getting the job done.

Those are the few beyond the superficial, "Oh that sounds cool," implications as there had to be some meat for it to stick. While I'd agree that Samurai may be the more correct title, once things have been out for a while in an incorrect form one has to reconcile things here as the TMNT aren't really what most would consider as covert mercenaries that is what Ninjas technically are. However, for those of us that grew up with cartoon depictions of Ninjas in this positive light this is what may stick for us and so there is also an element of nostalgia here too.

ContentLicense: CC BY-SA 2.5


问:
Algorithm to order array
Take for example this input array:

```<code>[2,7,1,4,9]
</code>```

For this input, I need to produce an array of total 23 elements which contains two elements of 2, seven elements of 7, one element of 1, four elements of 4 and nine elements of 9.
Example of output array:

```<code>[2,2,7,7,7,7,7,7,7,1,4,4,4,4,9,...]
</code>```

However, this array needs to be ordered in the way that minimizes the number of same elements appearing next to each other. The example of such array would be something like this:

```<code>[7,2,9,4,9,1,7,...]
</code>```

The primary goal is to minimize the number of the same adjacent elements.

Secondary goal is to distribute elements unbiased across resulting array if possible.

Any pseudo code or C#, java, ... would be helpful.

答:
The resulting array only really needs to separate the largest elements, any smaller element will be trivially separated by the larger elements. So if we have 9, 7, 4, and 2:

```<code>999999999
9797979797979799
97 97 97 97 97 97 97 94 9
</code>```

And now it's easy, because there are always enough spaces to insert smaller numbers (starting at the left)

```<code>974 974 974 972 972 97 97 94 9
</code>```

Title: Algorithm to order array

Body:
The resulting array only really needs to separate the largest elements, any smaller element will be trivially separated by the larger elements. So if we have 9, 7, 4, and 2:

999999999
9797979797979799
97 97 97 97 97 97 97 94 9

And now it's easy, because there are always enough spaces to insert smaller numbers (starting at the left)

974 974 974 972 972 97 97 94 9


问:
My architecture has a problem with views that required information from different objects. How can I solve this?
I am building an architecture like this:
These are my SW layers

```<code> ______________
|              |
|    Views     |
|______________|

 ______________
|              |
|Business Logic|
|______________|

 ______________
|              |
|  Repository  |
|______________|
</code>```

My views are going to generate my HTML to be sent to the user
Business logic is where all the business logics are
Repository is a layer to access the DB

My idea is that the repository uses entities (that are basically the representation of the tables, in order to perform DB queries.

The layers communicate between themselves using Business Objects, that are objects that represent the real-world-object itself. They can contain business rules and methods.

The views build/use DTOs, they are basically objects that have the information required to be shown on the screen. They expect also this kind of object on actions and, before calling the business logic, they create BO.

First question: what is your overall feeling about this architecture?

I've used similar architecture for some projects and I always got this problem:
If my view has this list to show :

```<code>Student1, age, course, Date Enrolled, Already paid?
</code>```

It has information from different BO.
How do you think one should build the structure?

These were the alternatives I could think of:

The view layer could call the methods to get the student, then the course it studies, then the payment information. This would cause a lot of DB accesses and my view would have the knowledge about how to act to generate this information. This just seems wrong for me.

I could have an "adapter object", that has the required information (a class that would have a properties Student, Course and Payment). But I would required one adapter object for each similar case, this may get very bad for big projects.

I still don't like them. Would you have ideas? How would you change the architecture to avoid this kind of problems?

@Rory:
I read the CQRS and I don't think this suits my needs. As taken from a link references in your link

Before describing the details of CQRS we need to understand the two main driving forces behind it: collaboration and staleness

That means: many different actors using the same object (collaboration) and once data has been shown to a user, that same data may have been changed by another actor – it is stale (staleness).

My problem is that I want to show to the user information from different BO, so I would need to receive them from the service layer. How can my service layer assemble and deliver this information?

Edit to @AndrewM:
Yes, you understood it correctly, the original idea was to have the view layer to build the BOs, but you have a very nice point about the creation of the BO inside the business layers.
Assuming I follow your advice and move the creation logic inside the business layer, my business layer interface would contain the DTOs, for instance

```<code>public void foo(MyDTO object)
</code>```

But as far as I understand, the DTO is tightly coupled to each view, so it would not be reusable by a second view. In order to use it, the second view would need to build a specific DTO from a specific view or I would have to duplicate the code in the business layer. Is this correct or am I missing something?

答:
Object-relational mappers like NHibernate want you to do all of your data processing using business objects. However, as you've recognised, pulling a whole aggregate out of the repository is a costly operation when all you want is one aspect of it. Why rehydrate a whole Customer, including all of their Orders and so on - potentially joining across a number of tables - when all you need to display on-screen is a FirstName? The problem balloons when you need a little information from a lot of aggregates.

The solution is Command/Query Responsibility Segregation. (I believe the idea is due to Greg Young.) An individual view needs a very specific set of information which an ORM may struggle to provide efficiently. So why not write view-specific queries which bypass the ORM, using a language which is designed for expressive, efficient querying? (You could use straight SQL, stored procedures, LINQ-to-SQL, HQL, or some other declarative language.) This way, you can optimise your queries to the nines when necessary - after all, reading data is far more common than writing data.

In a CQRS architecture, the domain model (and NHibernate) only exists to facilitate writing. Its entire job is to protect your business invariants and keep the database in a consistent state. Reading from the database is handled in a completely separate part of your application, known as the Thin Read Layer, which doesn't use the domain model at all.

Typically, in your thin read layer, you'll have one specialised query per view. This may seem wasteful but as Kent Beck and Martin Fowler say, "We think reuse is overrated (we just use)." The thin read layer is thin - it just pulls a specific set of data out of the DB as fast as it can. So queries are easy to write, which in turn makes them cheap to throw away when the view changes.

When you get serious about optimising your application for reading, you may realise your database schema is holding you back and you need to perform some denormalisation. However, denormalisation can have the effect of making writes to the database unfeasibly complex, making your domain model slow and harder to maintain. So, some people move their entire query side out to a separate database! This could take the form of a SQL database which has been optimised for reading, but you don't have to use SQL - your views might be most efficient with something like Mongo or Lucene.

In this type of system, the thin read layer has to watch for changes in the domain model. Typically, this is implemented using an asynchronous publish/subscribe pattern - the domain model raises events to which the read-side subscribes in order to update its cache. You should set up the message broker to record your events, so you can always reconstruct your projections in case something goes wrong or you need to spin up a new instance.

This architecture is easy to distribute, when the time comes to scale up your app. You'd set up one write-side database (with a domain model) to be the 'source of truth', and lots of thin read layers sitting on top of caches all around the world.


答:
This will be understood, whether you do it or not should depend on local (team or company) conventions.  Note that it makes less sense in the context of TDD as the TEST should be what determines that the method isn't implemented.

The short version is: use if you and your team consider it appropriate.

Title: Is it conventional to raise a NotImplementedError for methods whose implementation is pending, but not planned to be abstract?

Body:
I like to raise a NotImplementedError for any method that I want to implement, but where I haven't gotten around to doing it yet.  I might already have a partial implementation, but prepend it with raise NotImplementedError() because I don't like it yet.  On the other hand, I also like to stick to conventions, because this will make it easier for other people to maintain my code, and conventions might exist for a good reason.

However Pythons documentation for NotImplementedError states:

This exception is derived from RuntimeError. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method.

That is a much more specific, formal use case than the one I describe.  Is it a good, conventional style to raise a NotImplementedError simply to indicate that this part of the API is a work in progress?  If not, is there a different standardised way of indicating this?


问:
Reasons for moving from raw JavaScript to a JavaScript library
Being aware of the direct benefits of libraries having things wrapped in a package, making daily work easier, my question is leaning more towards the fact that many features not implemented in HTML/DOM/CSS, has become available using these libraries.

There is everything, from visual effects (13 a dozen) to more functional oriented, to choose from.

As I see it today, 2014, with HTML5 and CSS3, more and more of these libraries seems to have played there role, as a kind of a bridge covering the gap between older browsers non capabilites and the new ones ability to handle it built in.

Whats more, is that these libraries also seems to drop older browser support little by little.

This gives me as a developer a hard decision, if to upgrade to next version with more functionality and lose old browser support, or stay on an older version with less functionality but with old browser support and the need of custom development to achieve new functionality.

So my question is, is there anything else I might have missed, which could affect whether to implement a library as a base or use raw JavaScript and add a library when it is really needed?

答:
There are libraries like jQuery that truly become less relevant today due to browsers finally catching up.

On the other hand, there are utility belt libraries like Underscore that you'll end up reimplementing yourself on any moderately complex project. These are simple, focused utility functions that I like to use even on vanilla JS projects.

Then there are frameworks like AngularJS or Montage. These are wildly different beasts than jQuery. Whereas jQuery bridges browser gap, frameworks like AngularJS force you to adopt a completely different paradigm separating your UI in loosely-tied components that have declarative bindings to models. You won't need these for simple websites, but for highly interactive single-page apps you can't go far fiddling with DOM—even jQuery won't save you from managing view lifecycle, updating data in many places on the screen when it changes, client-side routing, etc. Think apps like Facebook, Twitter.

Then there's a neat niche for libraries that don't force you to rewrite all your code like AngularJS, but still allow to build rich JS apps. My current favorite is ReactJS by Facebook, its killer feature is one-way data flow and what you may call declarative DOM programming: you specify how DOM tree looks in different program states, and ReactJS calculates and applies minimum set of DOM operations needed to go from one state to another.

As you can see, the space for JS frameworks is vast, and you shouldn't dismiss all of them just because browsers are finally catching up with jQuery. There are more problems, and more solutions to client-side JS development, and the field is exploding right now.

ContentLicense: CC BY-SA 4.0


答:
If you want to bind events to dynamically loaded elements, you can utilize Event Bubbling. JQuery will help you with that! You'll need to bind the event with the on function(instead of click etc.) and use late selectors(not actual name - it's just me calling them that). For example:

HTML:

```<code><div id="add-stuff-here"></div>
</code>```

JavaScript:

```<code>$(function(){
        var addStuffHere=$('#add-stuff-here');
        addStuffHere.on('click','button[doit]',function(){
            var newButtonIndex = addStuffHere.children().length+1;
            var newButton = $('<button/>');
            newButton.text(newButtonIndex);
            if(1 == newButtonIndex%2){
                newButton.attr('doit', 'doit');
            }
            addStuffHere.append(newButton);
        });
        addStuffHere.append($('<button doit="doit">1</button>'));
});
</code>```

I bound the click event to the div, and gave it the late selector button[doit]. Now this event will apply to all children of the div that match the selector(the odd-numbered buttons - the even ones don't get doit). Clicking on these buttons will create new buttons, and if they are odd they'll also get the event because it is bound to the parent.

Behind the scenes the events bubble up to the containing elements, so the event launches on the button and bubbles up to the div where it's handled. Here JQuery works it's magic - When you have a late selector, JQuery identify the source of the event, and if it matches the late selector you'll JQuery will treat it like the child element's event. If you don't have a late selector JQuery will treat it like the container's event.

Title: When/Where to create/assign event handlers to its elements

Body:
If you want to bind events to dynamically loaded elements, you can utilize Event Bubbling. JQuery will help you with that! You'll need to bind the event with the on function(instead of click etc.) and use late selectors(not actual name - it's just me calling them that). For example:

HTML:

<div id="add-stuff-here"></div>

JavaScript:

$(function(){
        var addStuffHere=$('#add-stuff-here');
        addStuffHere.on('click','button[doit]',function(){
            var newButtonIndex = addStuffHere.children().length+1;
            var newButton = $('<button/>');
            newButton.text(newButtonIndex);
            if(1 == newButtonIndex%2){
                newButton.attr('doit', 'doit');
            }
            addStuffHere.append(newButton);
        });
        addStuffHere.append($('<button doit="doit">1</button>'));
});

I bound the click event to the div, and gave it the late selector button[doit]. Now this event will apply to all children of the div that match the selector(the odd-numbered buttons - the even ones don't get doit). Clicking on these buttons will create new buttons, and if they are odd they'll also get the event because it is bound to the parent.

Behind the scenes the events bubble up to the containing elements, so the event launches on the button and bubbles up to the div where it's handled. Here JQuery works it's magic - When you have a late selector, JQuery identify the source of the event, and if it matches the late selector you'll JQuery will treat it like the child element's event. If you don't have a late selector JQuery will treat it like the container's event.


答:
Another approach, which I used before learning of event bubbling, is to attach the events to the dynamically created elements. Doing this manually it cumbersome, so I've build some helper functions: registerJQueryFunction and applyJQueryTo. applyJQueryTo will invoke all the functions registered with registerJQueryFunction on an element(s), and those function will set the events.

This works even better if you have built a framework(even a wrapper framework) for the dynamic loading, as you can simply integrate applyJQueryTo into it and never worry about it.


答:
Fix random seed. For 1, 2, 5 and 12-sided dice, confirm that a few thousand rolls gives results including 1 and N, and not including 0 or N + 1. If by seem freak chance you get a set of random results that don't cover the expected range, switch to a different seed.

Mocking tools are cool, but just because they allow you to do a thing doesn't mean that thing should be done. YAGNI applies to test fixtures as much as features.

If you can easily test with unmocked dependencies, you pretty much always should; that way your tests will be focused on reducing defect counts, not just increasing test count. Excess mocking risks creating misleading coverage figures, which in turn can lead to postponing the actual testing to some later phase you perhaps never have time to get round to...

Title: What are good unit tests to cover the use case of rolling a die?

Body:
I'm trying to get to grips with unit testing.

Say we have a die which can has a default number of sides equal to 6 (but can be 4, 5 sided etc.):

```<code>import random
class Die():
    def __init__(self, sides=6):
        self._sides = sides

    def roll(self):
        return random.randint(1, self._sides)
</code>```

Would the following be valid/useful unit tests?

test a roll in the range 1-6 for a 6 sided die

test a roll of 0 for a 6 sided die

test a roll of 7 for a 6 sided die

test a roll in the range 1-3 for a 3 sided die

test a roll of 0 for a 3 sided die

test a roll of 4 for a 3 sided die

I'm just thinking that these are a waste of time as the random module has been around for long enough but then i think if the random module gets updated (say i update my Python version) then at least i'm covered.

Also, do I even need to test other variations of die rolls e.g. the 3 in this case, or is it good to cover another initialized die state?


问:
Why database as queue so bad?
I've just read this article, and I'm confused.

Let's imagine 1 webapp and 1 distinct application acting as "worker", both sharing the same database.

Oh, I said "sharing"..but what does the article warns about? :

Fourthly, sharing a database between applications (or services) is a
  bad thing. It’s just too tempting to put amorphous shared state in
  there and before you know it you’ll have a hugely coupled monster.

=> disagree. There are some cases where distinct applications still be part of the same unit, and therefore, notion of "coupling issue" makes no sense in this case.

Let's continue: The webapp handles client HTTP requests and may update at any time some aggregates (DDD term), generating the corresponding domain events.

The goal of the worker would be to handle those domain events by processing the needed jobs.

The point is:

How should events data be passed to the worker?

The first solution, as the read article promotes, would be to use RabbitMQ, being a great message-oriented middleware.

The workflow would be simple:

Any time the web dyno generates an event, it publishes it through RabbitMQ, which feeds the worker.

The drawback would be that nothing guarantees the immediate consistency between the commit of the aggregate update and the publishing of the event, without dealing with the potential sending failures... or hardware issues; that is another main issue.

Example: It would be possible that an event was published without a success of the aggregate update...resulting in an event representing a false representation of the domain model.

You could argue that global XA (two-phase commit) exists, but it's not a solution that fits all databases or middlewares.

So what could be a good solution to ensure this immediate consistency? :

IMO, storing the event in database, in the same local transaction as the aggregate update.

A simple asynchronous scheduler would be created and responsible of querying current unpublished events from database and send them to RabbitMQ, which in turn populates the worker.

But why needing an extra scheduler in webapp side and by the way: why needing RabbitMQ in this case?

By this solution, it appears logically, that the RabbitMQ could be unnecessary, especially because the database is shared.

Indeed, whatever the case, we saw that the immediate consistency involves a polling from database.

Thus, why wouldn't worker be responsible directly for this polling?

Therefore, I wonder why so many articles on the web criticizes hardly database queuing, while promoting message-oriented middleware.

Excerpt of the article:

Simple, use the right tool for the job: this scenario is crying out
  for a messaging system. It solves all the problems described above; no
  more polling, efficient message delivery, no need to clear completed
  messages from queues, and no shared state.

And immediate consistency, ignored ?

To sum up, it really seems that whatever the case is, meaning database shared or not, we need database polling.

Did I miss some critical notions?

Thanks

答:
If you are building a simple application with low traffic, there is something to be said about keeping another component out of your system.  It is very likely that not using a message bus is the right answer for you.  However, I would suggest building your system in a way you could swap out the database-based queue system for a middleware solution.  I agree with the article.  A database is not the right tool for queue based system, but it may be good enough for you.

Queue based system like RabbitMq are built around massive scale on moderate hardware.  Their architecture is able to achieve this by avoiding processes which make ACID compliant database system slow by their nature.  Since a message bus only needs to ensure a message is stored and successfully processed, it doesn't need to bother with locking and writing transaction logs.  Both of these concepts are absolutely required for an ACID system but are often a cause of contention.

Performance-wise it comes down to: you have an SQL table.  Lots of reads and lots of writes.  Both require some sort of locking to update rows, pages and indexes.  Your polling mechanism is constantly locking an index to do lookups on it.  This prevents writes from happening; at best they are queued.  The code doing the processing is also locking to update the status on the queue as they complete or fail.  Yes, you can do query optimization after optimization to get this to work, or you can use a system specifically designed for the work load you are asking.  A RabbitMq eats up this type of workload without even breaking a sweat; on top of that, you get to save your database from the workload giving it more room to scale doing other things.

Another thing to consider is most queue systems typically do not use a polling technique (some allow for HTTP, but recommend to avoid using for the receive side).  RabbitMq uses network protocols specifically designed for message buses such as AMPQ.

Edit:  Adding usage case.

The way I have used Rabbit is I have had an API endpoint which accepts a change which requires a heavily used database table.  This table is under constant contention and at times will not be able to save a change in a timely fashion from the API.  What I do instead is write the change request to a queue and then have a service which handles these messages as they are able.  If database contention occurs the queue simply grows and message processing is delayed.  Typically processing time down in the 14ms range, but in times of high contention we get up to 2-3 seconds.

Title: Why database as queue so bad?


问:
Building complex algorithms with TDD
I'm trying to adopt TDD in my daily programming practice.  I use it at work very effectively, but I'm having trouble with my personal projects where I'm using some complex algorithms.

The particular algorithm that makes me ask this question is the Extended Kalman Filter.  It's complex enough that I'm not confident in the code I've written, but it's simple enough that it's hard to break up.

I could write a test for the algorithm with an input and the expected output, but I'll do a lot of thrashing and shotgun coding in the middle because I don't have confidence in those intermediate steps.

If you've worked with reasonable complex algorithms and use TDD, what is your approach?

答:
TDD is not a substitute for design.

This is a common misconception about TDD, that you can somehow "grow" a coherent design from red-green-refactor.  You can't.  Your tests still need to be guided by your design skills.

If you're trying to figure out what to do between the input and output of  your method under test, it probably means that you're trying to do too much in a single method.  Think about what those intermediate steps should do.  Write tests for those intermediate steps, and write methods that pass those tests.

Title: Building complex algorithms with TDD


问:
Best way to migrate a series of code (v1, v2, etc) into a new VCS?
I am completely new to using VCS and haven't settled on Git or Hg, but I do know that I will be using it soon. My old project folder has versions of files labeled v1, v2, etc. How easily can I fold this into a new [local] repo? There are only a few sets of files with version counters (so commit, then copy paste, then commit is an option). I should also note that I am not a classically trained programmer but a self-taught former analytical chemist.</p>

答:
Copy, paste, & commit is fine.

Many years ago, when starting out a tiny software company with a developer who wasn't comfortable with CVS (the then-current best-of-breed VCS), I just told him to take daily snapshots of his workspace and we'd fix things later.  A few months down the road, I spent several days doing exactly this, even resetting my workstation clock so it looked like the commits happened on the date that matched the snapshot.  File additions and deletions complicate things, but you can automate that by running the appropriate command to recognize files that are missing in the snapshot (and must therefore be deleted) or never committed (and must therefore be added).  CVS, and early Subversion, littered the source tree with hidden subdirectories, which made for fun in cleaning up, but modern VCSes (including modern Subversion) don't have that problem.


问:
Design pattern for bidirectional signals/events
This problem feels rather basic, yet I've never known a great solution. I'm looking for a way for components in an application to notify each other while being as decoupled as possible (both at build/compile and run time), but also avoiding circular notifications in a way that components do not need to self-mitigate against. I happen to be hitting this issue (for the hundredth time) in JavaScript right now, but that is incidental.

Some means of decoupling include:

Dependency injection (DI). In this case I use require.js which allows, for instance, substituting mock implementations in unit tests by creating alternate require.config() setups.

Event dispatching. E.g. fooInstance.listen('action string', barInstance.actionHandler)

Publish/subscribe (aka pub/sub).

The last two are basically variants of the Observer pattern with different pros and cons.

The problem I want to solve is not specifically addressed by these patterns, and I'm not sure if its an implementation detail or if there is a pattern to apply:

fooObj sends a message (fires an event, whatever) that the "baz" property has changed

barObj.bazChanged() handles this event by calling its own setBaz() method

barObj.setBaz() fires an event that "baz" has changed

fooObj.bazChanged() handles this event ...

As a real case, imagine fooObj is a GUI component, with a slider for "tempo", and barObj is a music sequencing component that plays back a score. The slider should affect the tempo of the sequencer, but the score can contain tempo changes so when playing the sequencer should affect the slider position. A solution should be modeless.

One approach is to add guards, for example:

```<code>function handleTempoChanged(tempo) {
    if (this.tempo == tempo) return;
    ...
}
</code>```

This works but feels like a poor solution because it means every event handler needs to either assume it needs a guard, which is ugly boilerplate and often not required, OR needs to be aware of the other components in the system that would make a cycle possible. Arguably, this point is wrong, guards should always be used if the handler is going to fire a changed event directly or indirectly, but this still feels like boilerplate logic. This may be the only answer to my question...

Is there general case pattern to deal with potential cycles as described? Note that this is not about synchronous vs. asynchronous; either way the cycles can occur.

EDITED to reflect insight from commenters:

I realize it is possible to eliminate the boilerplate, using some sort of mixin. In pseudo-code:

```<code>class ObservablePropsMixin:

    // generic setter with gaurd
    function set(propName, value):
        if this[propName] = value: return
        this[propName] = value
        _fire(propName, value)

    // generic method to add listeners
    function observe(propName, handler):
        _observers[propName].add(handler)

    // private event dispatching method
    function _fire(propName, value):
        foreach observer in _observers[propName]:
            observer.call(propName, value)

    ...
</code>```

This is simplified to focus on my question, but a real mixin would implement other pubsub or event or signal semantics, analogous to any event dispatcher implementation. Components needing to be observers or observables would inherit/extend from the mixin (the above assumes some form of multiple or aggregate inheritance is possible in the language. This could be modified to work with composition instead, e.g. ObservableMixin.constructor(observedObject) rather than using "this".

答:
A number of years ago, I had a similar problem in real time system design. The general approach I took was to create a set of modules with each module having a number of facets: inputs, outputs, control, maintenance, repository and a couple of others. Each module was assigned to a level in the system -- sometimes the level was fairly arbitrary. In some cases, a module was split into parts, with lower level functions separated from higher level functions. In other cases, the facets were broken into levels (higher level inputs versus lower level inputs).

We established rules for how call-backs could be handled. The rules were based on directionality (up/down, left/right) and facets (inputs could only be connected to outputs). Rules were expressed as "this type of marble can only ever roll downhill" or "this ball can bounce higher".

Model-View-Controller has a set of rules that are similar. In addition, within the JSP environment, there are timing rules: certain observations can only be made at certain times. The MVC framework itself imposes the rules.

In your case, it sounds like you are trying to build the framework yourself. Thus, you must establish the syntax and semantics of your "observer language". Here is one approach you might want to play with:

Establish kinds of observations. The kinds are based on the impact of the observer on the state of the system. Establish relationships between kinds.

a) Display kind (View in MVC). The observed value is only ever formatted for viewing, and the value goes in only a single direction (towards the user, or towards a printed report).

b) Calculation kind. The observed value will take part in a calculation, likely with other observed values, and the result may, in turn, be observed. Circularity abounds and there must be infrastructure to identify convergence or divergence.

c) Input kind. User input such as form field or drop down. Result goes inward, towards the heart of the application. Display and Input kinds can be composed, of course, but they have a state relationship that prevents vicious circles.

d) Validater kind. Observes one or more values and rings a bell when things aren't right. Inputs and Validaters can be composed, again with state and timing relationships

...

By establishing a protocol or language or rules of engagement, you may be able to retain your sanity. :)

OwnerDisplayName: Jason Boyd


问:
How to measure the success of a small software project?
I'm part of a 7 person software development team which supports a company with a few thousand staff. Our team is putting together a quick review process for measuring the success of a software project. Projects are mostly internal, which means our "customers" are more often than not other staff. Projects are reasonably small (generally 100 to 1000 hours).

Our review process will need to have a few aspects to it, probably including:

A questionnaire sent to the customers (filled in by people in a variety of roles if possible, such as managers who may not be users of the software, and users), looking at the ease of use, quality of documentation, incident response, value for money, reliability.

Cost compared with the budget. Estimated development time compared with actual time would be looked at here too.

Security, if applicable.

Maintainability, such as how easy it is to log in as a particular user to replicate problems, and how easy the code is to follow.

Technical documentation, such as instructions on setting up development environments and test data.

Is there anything glaring I've missed, or anything that should have a particularly strong (or weak) focus?

答:
Beside anything you mention I'll add an agile methodology, like Scrum.

I would like to see something related to Scrum. I believe you can implement Scrum for greater the visibility of how your team is running or working on your projects. Scrum is great for handling imprecise or changing requirements. It will help you because it capture outstanding tasks on a visible backlog and, once a sprint starts, its tasks are immutable.


问:
Should I refactor large functions that mostly consist of one regex?
I just wrote a function that spans approximately 100 lines. Hearing that, you are probably tempted to tell me about single responsibilities and urge me to refactor. This is my gut instinct as well, but here is the issue: The function does one thing. It performs a complex string manipulation, and the function body consists mostly of one verbose regex, broken up into many lines that are documented. If I broke up the regex into multiple functions, I feel like I would actually lose readability, since I am effectively switching languages, and won't be able to take advantage of some features regexes offer. Here now is my question:

When it comes to string manipulation with regular expressions, are large function bodies still an anti-pattern? It seems like named capture groups serve a very similar purpose to functions. By the way, I have tests for every flow through the regex.

答:
I would say break it if it is breakable. from maintainability point of view and maybe resuability it makes sense to break it, but of course you have to consider natural of your function and how you get input and what it is going to return.

I remember I was working on parsing streaming chunked data into objects, so what I did basically was I divided it into two main parts, one was building complete unit of String out of encoded text and in second part parsing those units into data dictionary and organize them (could be random property for different object) and than updating or creating objects.

Also I could break each main part into several smaller and more specific functions so at end I had 5 different functions to do the whole thing and I could reuse some of the functions in different place.


答:
What you're encountering is the cognitive dissonance that comes from listening to people who favor slavish adherence to guidelines under the guise of "best practices" over reasoned decision making.

You've clearly done your homework:

The function's purpose is understood.

The workings of its implementation is understood (i.e., readable).

There are full-coverage tests of the implementation.

Those tests pass, meaning you believe the implementation to be correct.

If any of those points weren't true, I'd be first in line to say that your function needs work.  So there's one vote for leaving the code as-is.

The second vote comes from looking at your options and what you get (and lose) from each:

Refactor. This gains you compliance with someone's idea of how long a function should be and sacrifices readability.

Do nothing.  This maintains existing readability and sacrifices compliance with with someone's idea of how long a function should be.

This decision comes down to which you value more:  readability or length.  I fall into the camp that believes length is nice but readability is important and will take the latter over the former any day week.

Bottom line: if it isn't broken, don't fix it.

Title: Should I refactor large functions that mostly consist of one regex?

Body:
I just wrote a function that spans approximately 100 lines. Hearing that, you are probably tempted to tell me about single responsibilities and urge me to refactor. This is my gut instinct as well, but here is the issue: The function does one thing. It performs a complex string manipulation, and the function body consists mostly of one verbose regex, broken up into many lines that are documented. If I broke up the regex into multiple functions, I feel like I would actually lose readability, since I am effectively switching languages, and won't be able to take advantage of some features regexes offer. Here now is my question:

When it comes to string manipulation with regular expressions, are large function bodies still an anti-pattern? It seems like named capture groups serve a very similar purpose to functions. By the way, I have tests for every flow through the regex.


问:
Passing a Scala function to a Java 8 method
The following Scala code works and can be passed to a Java method expecting a function.  Is there a cleaner way to do this?  Here's my first pass:

```<code>val plusOne = new java.util.function.Function[Int,Int] {
  override def apply(t:Int):Int = t + 1

  override def andThen[V](after:function.Function[_ >: Int, _ <: V]):
    function.Function[Int, V] = ???

  override def compose[V](before:function.Function[_ >: V, _ <: Int]):
    function.Function[V, Int] = ???
}
</code>```

Here's my second pass - it uses a generic wrapper for the Java-8 Function interface to make the Scala syntax simpler:

```<code>// Note: Function1 is Scala's functional interface,
// Function (without the 1) is Java 8's.
case class JavaFunction1[U,V](f:Function1[U,V]) extends Function[U,V] {
  override def apply(t: U): V = f(t)
  override def compose[T](before:Function[_ >: T, _ <: U]):
    Function[T, V] = ???
  override def andThen[W](after:Function[_ >: V, _ <: W]):
    Function[U, W] = ???
}

val plusOne = JavaFunction1((x:Int) => x + 1)
val minusOne = JavaFunction1((x:Int) => x - 1)
</code>```

Can we do better?

As a follow-up, is there any chance that Scala will someday use the invoke-dynamic op-code as Java 8 does for its first-class function application?  Will that make everything magically work, or will there still need to be a syntactic conversion?

答:
You can make the conversion implicit:

```<code>implicit def toJavaFunction[U, V](f:Function1[U,V]): Function[U, V] = new Function[U, V] {
  override def apply(t: U): V = f(t)

  override def compose[T](before:Function[_ >: T, _ <: U]):
    Function[T, V] = toJavaFunction(f.compose(x => before.apply(x)))

  override def andThen[W](after:Function[_ >: V, _ <: W]):
    Function[U, W] = toJavaFunction(f.andThen(x => after.apply(x)))
}

implicit def fromJavaFunction[U, V](f:Function[U,V]): Function1[U, V] = f.apply
</code>```

You shouldn't actually need to override compose and andThen, but maybe Scala compiler doesn't know about Java 8 default interface methods yet. (EDIT: it should work in 2.10.3.)

Also, you should be able to assign Scala lambdas (i.e. x => ...) to Function and any other SAM types in Scala 2.11, and Java 8 lambdas to Function1. (EDIT: this actually got added in Scala 2.12, not 2.11.)

Body:
You can make the conversion implicit:

implicit def toJavaFunction[U, V](f:Function1[U,V]): Function[U, V] = new Function[U, V] {
  override def apply(t: U): V = f(t)

  override def compose[T](before:Function[_ >: T, _ <: U]):
    Function[T, V] = toJavaFunction(f.compose(x => before.apply(x)))

  override def andThen[W](after:Function[_ >: V, _ <: W]):
    Function[U, W] = toJavaFunction(f.andThen(x => after.apply(x)))
}

implicit def fromJavaFunction[U, V](f:Function[U,V]): Function1[U, V] = f.apply

You shouldn't actually need to override compose and andThen, but maybe Scala compiler doesn't know about Java 8 default interface methods yet. (EDIT: it should work in 2.10.3.)

Also, you should be able to assign Scala lambdas (i.e. x => ...) to Function and any other SAM types in Scala 2.11, and Java 8 lambdas to Function1. (EDIT: this actually got added in Scala 2.12, not 2.11.)


答:
Sometimes a longer function that does one thing is the most appropriate way to handle a unit of work. You can easily get into very long functions when you start dealing with querying a database (using your favorite query language). To make a function (or method) more readable while limiting it to its stated purpose is what I would consider the most desirable outcome of a function.

Length is an arbitrary "standard" when it comes to code size. Where a 100 line function in C# may be considered longish, it would be tiny in some versions of assembly. I have seen some SQL queries that were well into the 200 lines of code range that returned one very complicated set of data for a report.

Fully working code, that is as simple as you can reasonably make it is the goal.

Don't change it just because it is long.


答:
One can use TDD for complex algorithms. Write plenty of clear yet meaningful tests and use them to design your program. if there is randomization used in the algorithm use some sort of dependency injection and test randomization separately. TDD is one of the many methods you will use to write high quality algorithms: other being code reviews, logging etc..

I could write a test for the algorithm with an input and the expected
  output,

Do not write "a" test.. TDD is not write one test at a time. Write multiple tests first that checks various bounds and standard inputs of the algorithm..

Title: Building complex algorithms with TDD

Body:
I'm trying to adopt TDD in my daily programming practice.  I use it at work very effectively, but I'm having trouble with my personal projects where I'm using some complex algorithms.

The particular algorithm that makes me ask this question is the Extended Kalman Filter.  It's complex enough that I'm not confident in the code I've written, but it's simple enough that it's hard to break up.

I could write a test for the algorithm with an input and the expected output, but I'll do a lot of thrashing and shotgun coding in the middle because I don't have confidence in those intermediate steps.

If you've worked with reasonable complex algorithms and use TDD, what is your approach?


答:
Honestly, your function may "do one thing", but  as you stated by yourself

I could start breaking up the regex into multiple functions,

which means your reg ex code does a lot of things. And I guess it could be broken down into smaller, individually testable units. However, if this is a good idea is not easy to answer, (especially without seeing the actual code). And the correct answer may be neither "yes" or "no", but "not yet, but next time you have to change something in that reg exp".

but feel like I would actually lose readability that way, since I am effectively switching languages

And this is the core point - you have a piece of code written in reg ex language. This language does not provide any good means of abstraction in itself (and I don't consider "named capture groups" as a replacement for functions). So refactoring "in the reg ex language" is not really possible, and interweaving smaller reg exps with the host language may not actually improve readability (at least, you feel so, but you have doubts, otherwise your would not have posted the question). So here is my advice

show your code to another advanced developer (maybe on https://codereview.stackexchange.com/) to make sure others think about readability the way you do. Be open to the idea that others may not find a 100 line reg exp as readable as you. Sometimes the notion of "its not easily breakable into smaller pieces" can be overcome just by a second pair of eyes.

observe the actual evolvability - does your shiny reg exp still look so good when new requirements arrive and you have to implement and test them? As long as your reg exp works, I would not touch it, but whenever something has to be changed, I would reconsider if it was really a good idea to put everyhing into this one big block - and (seriously!) rethink if splitting into smaller pieces would not be a better option.

observe the maintainability - can you effectively debug the reg exp in the current form very well? Especially after you have to change something, and now your tests tell you that something is wrong, do you have a reg exp debugger helping you to find the root cause? If debugging gets hard, that would also be a occasion to reconsider your design.


答:
Congratulations on accepting the simple task of solving one of the most controversial aspects of software development - measuring software developer value.

My advise is to start with a very clear understanding of what the intention of how this analysis is going to be used, as that 'flavours' what kinds of metrics are appropriate, and how effective you are going to be at collecting that that information.

Possible goals include:

Understanding why some projects are perceived as more successful than others, and identifying what things can be changed to increase chances of success in the future.

Performance reviews of individual software development team members

Calculating corporate return on investment figures for projects to asses viability of the current approach.

Understanding value added by the software team to the business as a whole.

There may well be more in this list.

When you have a clear understanding of the goal, you are much more likely to get good advice on the types of data you are needing. The types of questions you currently list seem to imply you are heading more towards 3 and 4

Title: How to measure the success of a small software project?

Body:
I'm part of a 7 person software development team which supports a company with a few thousand staff. Our team is putting together a quick review process for measuring the success of a software project. Projects are mostly internal, which means our "customers" are more often than not other staff. Projects are reasonably small (generally 100 to 1000 hours).

Our review process will need to have a few aspects to it, probably including:

A questionnaire sent to the customers (filled in by people in a variety of roles if possible, such as managers who may not be users of the software, and users), looking at the ease of use, quality of documentation, incident response, value for money, reliability.

Cost compared with the budget. Estimated development time compared with actual time would be looked at here too.

Security, if applicable.

Maintainability, such as how easy it is to log in as a particular user to replicate problems, and how easy the code is to follow.

Technical documentation, such as instructions on setting up development environments and test data.

Is there anything glaring I've missed, or anything that should have a particularly strong (or weak) focus?


答:
You could always break up the regex into sub-regexes, and gradually compose the final expression. This could aid comprehension for a very large pattern, particularly if the same sub-pattern is repeated many times. For example in Perl;</p>

```<code>my $start_re = qr/(?:\w+\.\w+)/;
my $middle_re = qr/(?:DOG)|(?:CAT)/;
my $end_re = qr/ => \d+/;

my $final_re = $start_re . $middle_re . $end_re;
# or:
# my $final_re = qr/${start_re}${middle_re}${end_re}/
</code>```

Body:
You could always break up the regex into sub-regexes, and gradually compose the final expression. This could aid comprehension for a very large pattern, particularly if the same sub-pattern is repeated many times. For example in Perl;

my $start_re = qr/(?:\w+\.\w+)/;
my $middle_re = qr/(?:DOG)|(?:CAT)/;
my $end_re = qr/ => \d+/;

my $final_re = $start_re . $middle_re . $end_re;
# or:
# my $final_re = qr/${start_re}${middle_re}${end_re}/


问:
MVC: How to Implement Linked Views?
I'm developing a java application to visualize time series. I need (at least) three linked views, meaning that interaction with one of them updates the others.

The views are:

A list represents the available and currently selected time series. The selected time series are used as input for subsequent computations. Changing the selection should update the other views.

A line chart displays the available and selected time series. Time series should be selectable from here by clicking on them.

A bar chart shows aggregated data on time series. When zooming in to a period of time, the line chart should zoom in to the same period (and vice versa).

How to implement this nicely, from a software engineering point of view? I.e. I'd like to write reusable and clear, maintainable code. So I thought of the MVC pattern.

At first I liked the idea of having the three view components observing my model
class and to refresh views upon being notified. But then, it didn't feel right to store view related data in the model. Storing e.g. the time series selection or plot zoom level in the model makes implications about the view which I wouldn't want in a reusable model.

On the other hand, having the controllers observe each other results in a lot of dependencies. When adding another view, I'd have to register all other views as observer of the new view and vice versa, passing around many references and introducing dependencies. Maybe another "model" storing only view-related data would be the solution?

答:
The 'active time series' and the 'zoom level' have slightly different consequences and have therefor different considerations where they can best be handled.

For the 'active time series', this can best be recorded in the model. The reason is that, if there is a component that could make modifications to a time series, then it is better if the model already knows which one is being operated on rather than having to pass it to the model each time you need to access the data. That also allows for a (future) optimization that the inactive time series are discarded from memory.

The zoom level is a UI concept that should ideally not be known to the model. One solution is to have a single controller that handles zoom events and that controller updates all the view with the change in zoom level (it is then up to the view what it does with the information).

Another option is to introduce a special "zoom model" that handles the zoom updates.

A completely different way to look at the zoom level is to regard it similar to showing a paginated set of results (with a variable page size). Sometimes, pagination is pushed to the model to provide an optimization opportunity for not keeping the entire model in memory.

Title: MVC: How to Implement Linked Views?


问:
How to manage focus for a small set of simple widgets
I'm developing a set of simple widgets for a small (128x128) display.

For example I'd like to have a main screen with an overlay menu which I can use to toggle visibilty of main screen elements. Each option would be an icon with a box around it while it is selected. Button (left, up, right, down, enter) events should be given to the widget that has "focus".

Focus is a simple thing to understand when using a GUI, but I'm having trouble implementing this. Can you suggest a simple concept for managing focus and input events? I have these simple ideas:

Only one widget can have focus, so I need a single pointer to that widget.

When this widget gets some kind of "cycle" input (as in "highlight the next item in this list"), the focus is given to a different widget.

a widget must have a way of telling the application which widget the focus is given to next.

if a widget cannot give a "next focus" hint, the application must be able to figure out where the focus should go.

Widgets are currently structured like this:

A widget can have a parent, which is passed to the constructor. Widgets are created statically, as I want to avoid dynamic memory allocation (I only have 16kB of RAM and I'd like to have control over that).

widgets have siblings, implemented as an intrusive linked list (they have a next member). A parent has a pointer to the head of its list of children.

Input events are arguments to the widgets buttonEvent methods which can accept or ignore that event. If it ignores the event, it can pass the event to its parent.

My Questions:

How can I manage focus for these widgets?

Am I making this too complicated?

答:
Here is what I have now, and I think it's not over-engineered and does its job of managing focus (i.e. which widget gets my button events?)

I have an abstract widget class that maintains a static pointer to an abstract widget, focus_.

A widget has a protected property, acceptsFocus_ that is used to enable focus for that widget (or not). This is more or less a constant property, I think.

Focus can be given to a widget with a public method. If it doesn't accept focus, focus is passed to the parent widget (which in turn can accept focus or not, you get the idea). This sets the static focus_ to point to the first widget that accepted it.

When a widget is constructed, it gets focus. This might not be necessary, but I thought it might be handy just in case I forget to set the focus to some widget when the whole app is initialized. On the other hand, I might end up wondering why something unexpected happens when I press a button.

If I don't totally mess things up, this ensures that button events will eventually end up being handled by something.


问:
Writing tests for two methods that share functionality
I'm writing some tests for a NodeJS module, but this question can apply for any language / platform. I've got the following situation:

```<code>// in moduleA.js

exports.foo = function (var1, var2) {
    // do something to var1 and var2 here

    baz(var1, var2);
};

exports.bar = function (var1, var2) {
    // do something completely different to var1 and var2 here

    baz(var1, var2);
};

function baz(var1, var2) {
    // do something to var1 and var2 yet again that both foo and bar need

    moduleB.doSomething(var1, var2);
}
</code>```

So, both foo and bar are public methods of moduleA. They've got some specific functionality (they do different things to var1 and var2) but also some shared functionality (to keep things DRY I've moved it into a private method, baz) and then they both call a public method on moduleB.

I've stubbed out moduleB so I know exactly what's going on after foo and bar have been called. I'm writing tests for foo and bar's specific functionality but I'm not 100% sure how to approach testing the shared functionality in baz.

It seems to me I've got three options:

write identical tests for both foo and bar that test for the things in baz

write a single test for foo and not write the same test for bar since know that baz works

expose baz as another public method for the module and test it separately.

I'm leaning towards the first option, but I feel I might be missing something.

答:
The test for moduleB.doSomething() doesn't belong into this test at all, except incidentally. It should be in the test for module B.

If baz were private to its module, and whatever it does is part of the public contract for several routines that use it, then its effects would have to be tested. As it is, the most you should do is query your B mock object whether baz was called, not whether it did its job.


答:
The key its to think in test for feature/behavior not in test for methods.

Its difficult without real names, but, "foo" exists to offer some behavior, the same with "bar", you simply need tests to check that the behavior of foo is correct and other to verify the behavior of "bar", when you discover that this two methods shared some internal functionality and decide to make a refactor your test remain the same, and thanks to that you can be sure that your refactor don't break any functionality.

I know that its probably generic advice, but its really difficult without a concrete example.

Title: Writing tests for two methods that share functionality

Body:
I'm writing some tests for a NodeJS module, but this question can apply for any language / platform. I've got the following situation:

```<code>// in moduleA.js

exports.foo = function (var1, var2) {
    // do something to var1 and var2 here

    baz(var1, var2);
};

exports.bar = function (var1, var2) {
    // do something completely different to var1 and var2 here

    baz(var1, var2);
};

function baz(var1, var2) {
    // do something to var1 and var2 yet again that both foo and bar need

    moduleB.doSomething(var1, var2);
}
</code>```

So, both foo and bar are public methods of moduleA. They've got some specific functionality (they do different things to var1 and var2) but also some shared functionality (to keep things DRY I've moved it into a private method, baz) and then they both call a public method on moduleB.

I've stubbed out moduleB so I know exactly what's going on after foo and bar have been called. I'm writing tests for foo and bar's specific functionality but I'm not 100% sure how to approach testing the shared functionality in baz.

It seems to me I've got three options:

write identical tests for both foo and bar that test for the things in baz

write a single test for foo and not write the same test for bar since know that baz works

expose baz as another public method for the module and test it separately.

I'm leaning towards the first option, but I feel I might be missing something.


答:
Unit tests shouldn't care about implementation details. Unit tests need to check that the the function returns the expected result, causes the expected side effects(and, if possible, not causing any other side effects), and throws the expected exceptions. How the functions does it should not concern the unit tests, just like it shouldn't concern the user of the module.

You don't need to unit-test baz(unless it's a module internal unit test) because it's not part of the module's API. That means that you should be able to remove it, rename it, or change it's functionality as long as the module's public functions still work, and neither the user code that uses the module nor the unit tests should change.

With this approach, it's easy to see that you should choose the first option - write unit tests for both foo and bar. The unit tests shouldn't care about baz, since you should be able to refactor it out of foo and/or bar, or to create a new version of it - baz2 - which bar will use while foo keep using original baz, or change some execution path of baz that neither foo nor bar should ever invoke. Those chances do not affect the module user, so they should not affect the unit test either.

If baz has some side-effects that foo activates, as far the the module user and the unit tests care those are side-effects of foo, so you should test them accordingly.


问:
Don't Repeat Yourself across integration-test code and production code?
I totally believe in not repeating yourself in production code. I've accepted the idea that you shouldn't repeat yourself within test code. But what happens when you have production services that would simplify test code?

Let me pose an example. We have a service that accesses the Doohickey API. The Doohickey API is complex, by necessity, and we have a bunch of code to simplify it for our needs.

Now I need to write some automated tests for our service. My tests need to set up data in the service and it would be really handy to reuse that facade. But then I get into an argument with myself, that goes roughly like this:

"If you introduce a bug in the Facade, the test might not show it."

"But, if you just take a copy, then when Dohickey Inc upgrade their API, you need to make the change in two places."

"True, but maybe that's a good thing. We can upgrade production code first, manage test data using the old, known, still-supported API and test the new version thoroughly."

And then I think maybe I'm overthinking the problem. Does anyone have experience with this kind of issue? If so, which way did you go, and did you regret it at all later?

Edit: Early comments suggest a more specific example is required.

Say I have a service that can create a product AND create an order. I have the following test to write ...

```<code>Given that product X exists
When customer Y orders product X
Then an order should exist for customer Y, including only product X
</code>```

For the "When" part of this, I contact my service, which uses a facade around the Dohickey Purchasing API to create the order.

The "Given" and "Then" steps should create a product and get an order, but they shouldn't go through the service to do so. Perhaps my service doesn't have that functionality, and if it does then I will test it elsewhere.

BUT the facade that lives within the service would make the test code much simpler. So should I reference the production code and use it or copy / rewrite the facade?

答:
In your scenario i probably make diferent test:

Unit test of my model/business logic. In this test i mock the abstraction created on Doohickey API. With this test i have confidence in my business logic.

One contract test for the abstraction over Doohickey API. With this test i verify that my code work correctly with the API and protect me of possible changes in the APi.

Probably i write some integration/system test, in this test i need like you say the Doohickey abstraction to insert data, i use it and don't duplicate code. With this test i have confidence in that all the pieces of my system work together.

If the code for inserting data breaks two test breaks in my system, the contract test and the system test, in fact, when its usual that when some unit or contract test fails one or more systems test fails too. But this give you a lot of information, you know with the unit/contract test the exact piece of code that fails and you know with the systems test the feature that is broken in your system as a result.


答:
"If you introduce a bug in the Facade, the test might not show it."

If you don't use the Facade, you will still have to "set up data in the service" (as you described it), so you need to write at least equivalent code. Who says that you don't introduce a bug right there? Or maybe there is a bug already in the facade in the first place and when you duplicate the facade code, what makes you sure you won't copy the bug either?

So I don't see any real reason not to reuse the facade code in your tests - I don't think the chances really get higher that you overlook some errors that way.

Title: Don't Repeat Yourself across integration-test code and production code?

Body:
I totally believe in not repeating yourself in production code. I've accepted the idea that you shouldn't repeat yourself within test code. But what happens when you have production services that would simplify test code?

Let me pose an example. We have a service that accesses the Doohickey API. The Doohickey API is complex, by necessity, and we have a bunch of code to simplify it for our needs.

Now I need to write some automated tests for our service. My tests need to set up data in the service and it would be really handy to reuse that facade. But then I get into an argument with myself, that goes roughly like this:

"If you introduce a bug in the Facade, the test might not show it."

"But, if you just take a copy, then when Dohickey Inc upgrade their API, you need to make the change in two places."

"True, but maybe that's a good thing. We can upgrade production code first, manage test data using the old, known, still-supported API and test the new version thoroughly."

And then I think maybe I'm overthinking the problem. Does anyone have experience with this kind of issue? If so, which way did you go, and did you regret it at all later?

Edit: Early comments suggest a more specific example is required.

Say I have a service that can create a product AND create an order. I have the following test to write ...

```<code>Given that product X exists
When customer Y orders product X
Then an order should exist for customer Y, including only product X
</code>```

For the "When" part of this, I contact my service, which uses a facade around the Dohickey Purchasing API to create the order.

The "Given" and "Then" steps should create a product and get an order, but they shouldn't go through the service to do so. Perhaps my service doesn't have that functionality, and if it does then I will test it elsewhere.

BUT the facade that lives within the service would make the test code much simpler. So should I reference the production code and use it or copy / rewrite the facade?


问:
Citations for inadvisability of globally unique password
I am having a disagreement with a client about the user authentication process for a system. The nub of it is that they want each user to have a globally unique password (i.e. no two users can have the same password).

I have wheeled out all the obvious arguments against this:

it's a security vulnerability,

it confuses identification with authentication,

it's pointless, etc.,

but they are insisting that there is nothing wrong with this approach.

I have done various gGoogle searches looking for authoritative (or semi-authoritative , or even just independent) opinions on this, but can't find any (mainly it's just such an obvious faux pas that it doesn't seem worth warning against, as far as I can tell).  Can anybody point me towards any such independent opinion, please?

EDIT: Thanks for all your answers, but I already understand the problems with this proposed approach/requirement, and can even explain them to the client, but the client wont't accept them, hence my request for independent and/or authoritative sources.

I'd also found the Daily WTF article, but it suffers from the problem that Jon Hopkins has pointed out - that this is such a self-evident WTF that it doesn't seem worth explaining why.

And yes, the passwords are going to be salted and hashed. In which case global uniqueness might well be difficult to ensure, but that doesn't solve my problem - it just means that I have a requirement that the client won't budge on, that's not only ill-advised, but is also difficult to implement. And if I was in a position to say "I'm not budging on salting and hashing", then I'd be in a position to say "I'm not implementing globally unique passwords".

Any pointers to independent and/or authoritative sources for why this is a bad idea still gratefully received...

答:
Whenever a client tries to create a password that already exists, it receives feedback that some user already uses that password, usually a violation of the privacy agreement.

Next to that, usernames are much easier to guess (and if there is a forum, you could just find alot of usernames there) and you're hinting the user ways to hack the website.

There should be some page on the internet somewhere that describes the privacy agreement violation part, other than that it's just common sense: they'd basically be giving someone a key and a list of home addresses.

EDIT: Not close to authorative, but perhaps helpful after you explain them what WTF means: http://thedailywtf.com/Articles/Really_Unique_Passwords.aspx


答:
The general solution to avoid repeating boilerplate is to pull it out into its own class.  In this case, you would usually create a Publisher class that handles avoiding cycles for you.

```<code>var tempoPublisher = new NumericPublisher();

tempoPublisher.onTempoChange(moveTempoSliderWidget);
tempoPublisher.onTempoChange(changeSequencerTempo);

tempoSliderWidget.onSlide(function (percentage) {
    tempoPublisher.publish(percentage * maxTempo);
});
</code>```

In your NumericPublisher.publish() you put your guard.  Then no matter how many NumericPublishers or components you create, you only need the guard in one place.

This also breaks the dependencies of the components on each other.  They only need to know about the tempoPublisher, which can be injected using DI.

Title: Design pattern for bidirectional signals/events

Body:
This problem feels rather basic, yet I've never known a great solution. I'm looking for a way for components in an application to notify each other while being as decoupled as possible (both at build/compile and run time), but also avoiding circular notifications in a way that components do not need to self-mitigate against. I happen to be hitting this issue (for the hundredth time) in JavaScript right now, but that is incidental.

Some means of decoupling include:

Dependency injection (DI). In this case I use require.js which allows, for instance, substituting mock implementations in unit tests by creating alternate require.config() setups.

Event dispatching. E.g. fooInstance.listen('action string', barInstance.actionHandler)

Publish/subscribe (aka pub/sub).

The last two are basically variants of the Observer pattern with different pros and cons.

The problem I want to solve is not specifically addressed by these patterns, and I'm not sure if its an implementation detail or if there is a pattern to apply:

fooObj sends a message (fires an event, whatever) that the "baz" property has changed

barObj.bazChanged() handles this event by calling its own setBaz() method

barObj.setBaz() fires an event that "baz" has changed

fooObj.bazChanged() handles this event ...

As a real case, imagine fooObj is a GUI component, with a slider for "tempo", and barObj is a music sequencing component that plays back a score. The slider should affect the tempo of the sequencer, but the score can contain tempo changes so when playing the sequencer should affect the slider position. A solution should be modeless.

One approach is to add guards, for example:

```<code>function handleTempoChanged(tempo) {
    if (this.tempo == tempo) return;
    ...
}
</code>```

This works but feels like a poor solution because it means every event handler needs to either assume it needs a guard, which is ugly boilerplate and often not required, OR needs to be aware of the other components in the system that would make a cycle possible. Arguably, this point is wrong, guards should always be used if the handler is going to fire a changed event directly or indirectly, but this still feels like boilerplate logic. This may be the only answer to my question...

Is there general case pattern to deal with potential cycles as described? Note that this is not about synchronous vs. asynchronous; either way the cycles can occur.

EDITED to reflect insight from commenters:

I realize it is possible to eliminate the boilerplate, using some sort of mixin. In pseudo-code:

```<code>class ObservablePropsMixin:

    // generic setter with gaurd
    function set(propName, value):
        if this[propName] = value: return
        this[propName] = value
        _fire(propName, value)

    // generic method to add listeners
    function observe(propName, handler):
        _observers[propName].add(handler)

    // private event dispatching method
    function _fire(propName, value):
        foreach observer in _observers[propName]:
            observer.call(propName, value)

    ...
</code>```

This is simplified to focus on my question, but a real mixin would implement other pubsub or event or signal semantics, analogous to any event dispatcher implementation. Components needing to be observers or observables would inherit/extend from the mixin (the above assumes some form of multiple or aggregate inheritance is possible in the language. This could be modified to work with composition instead, e.g. ObservableMixin.constructor(observedObject) rather than using "this".

Body:
The general solution to avoid repeating boilerplate is to pull it out into its own class.  In this case, you would usually create a Publisher class that handles avoiding cycles for you.

var tempoPublisher = new NumericPublisher();

tempoPublisher.onTempoChange(moveTempoSliderWidget);
tempoPublisher.onTempoChange(changeSequencerTempo);

tempoSliderWidget.onSlide(function (percentage) {
    tempoPublisher.publish(percentage * maxTempo);
});

In your NumericPublisher.publish() you put your guard.  Then no matter how many NumericPublishers or components you create, you only need the guard in one place.

This also breaks the dependencies of the components on each other.  They only need to know about the tempoPublisher, which can be injected using DI.