问:
Is it fair to say that "macros don't compose"?
On this blog post aphyr (who is a brilliant programmer) states:

Clojure macros come with some important restrictions. Because they’re expanded prior to evaluation, macros are invisible to functions. They can’t be composed functionally–you can’t (map or ...), for instance.

The classic example of this is:

```<code>(reduce and [true true false true])
;RuntimeException
</code>```

Yet we can write:

```<code>(reduce #(and %1 %2) [true true false true])
;false
</code>```

Is 'macros don't compose' a valid claim? Surely the only  valid point is that macros are not first class functions and shouldn't be treated as such.

答:
I think this depends on what you mean by "compose". I would say that it's mostly true but can be taken too far.

First, note that in the quote you cited aphyr didn't say "macros don't compose"; the phrase was "can't be composed functionally". That more limited claim is indisputably true. Macros in Clojure aren't values[1]. They can't be passed as arguments to other functions or macros, can't be returned as the result of computations, and can't be stored in data structures.

There are, of course, ways to work around these limitations. Besides your #(and %1 %2) example, there's a sense in which the code below represents composition.

```<code>(ns some.macros
  (:refer-clojure :exclude [when when-not]))

(defmacro when [test & body]
  `(cond ~test (do ~@body)))

(defmacro when-not [test & body]
  `(when (not ~test) ~@body))
</code>```

I intentionally used cond rather than if in the definition of when because cond is itself a macro.

But, back to the larger point, #(and %1 %2) isn't really an argument that macros compose, it's an argument that you can use macros within functions. And, because we have many powerful ways of working with functions, this is generally the best way to go. Use macros (when functions aren't appropriate) to abstract away boilerplate, repetitive code, but, when possible, ultimately expose as much of your API as possible as functions so that they can be stored in hash-maps, mapped over sequences of widgets, negated with complement, juxtaposed with juxt, and so on.

[1] It would be difficult for it to be otherwise. Imagine if macros were values and could be passed as arguments to functions. How could you compile code that used such a macro, given that its expansion wouldn't be known until runtime (and could vary between invokations of the function)?

Addendum

As a point of interest, consider that macros are functions, they're just treated specially by the compiler.

Check this out:

```<code>some.macros> (defn when [&form &env test & body]
               `(cond ~test (do ~@body)))
#<Var@1a37b98:
  #<macros$eval7806$when__7807 some.macros$eval7806$when__7807@d1cf9c>>
some.macros> (when nil nil true 1 2)
(clojure.core/cond true (do 1 2))
some.macros> (. #'when (setMacro))
nil
some.macros> (when true 1 2)
2
</code>```

This is, in fact, exactly how defmacro works. (See here for an explanation of the &form and &env pseudo-arguments).

Body:
I think this depends on what you mean by "compose". I would say that it's mostly true but can be taken too far.

First, note that in the quote you cited aphyr didn't say "macros don't compose"; the phrase was "can't be composed functionally". That more limited claim is indisputably true. Macros in Clojure aren't values[1]. They can't be passed as arguments to other functions or macros, can't be returned as the result of computations, and can't be stored in data structures.

There are, of course, ways to work around these limitations. Besides your #(and %1 %2) example, there's a sense in which the code below represents composition.

(ns some.macros
  (:refer-clojure :exclude [when when-not]))

(defmacro when [test & body]
  `(cond ~test (do ~@body)))

(defmacro when-not [test & body]
  `(when (not ~test) ~@body))

I intentionally used cond rather than if in the definition of when because cond is itself a macro.

But, back to the larger point, #(and %1 %2) isn't really an argument that macros compose, it's an argument that you can use macros within functions. And, because we have many powerful ways of working with functions, this is generally the best way to go. Use macros (when functions aren't appropriate) to abstract away boilerplate, repetitive code, but, when possible, ultimately expose as much of your API as possible as functions so that they can be stored in hash-maps, mapped over sequences of widgets, negated with complement, juxtaposed with juxt, and so on.

[1] It would be difficult for it to be otherwise. Imagine if macros were values and could be passed as arguments to functions. How could you compile code that used such a macro, given that its expansion wouldn't be known until runtime (and could vary between invokations of the function)?

Addendum

As a point of interest, consider that macros are functions, they're just treated specially by the compiler.

Check this out:

some.macros> (defn when [&form &env test & body]
               `(cond ~test (do ~@body)))
#<Var@1a37b98:
  #<macros$eval7806$when__7807 some.macros$eval7806$when__7807@d1cf9c>>
some.macros> (when nil nil true 1 2)
(clojure.core/cond true (do 1 2))
some.macros> (. #'when (setMacro))
nil
some.macros> (when true 1 2)
2

This is, in fact, exactly how defmacro works. (See here for an explanation of the &form and &env pseudo-arguments).


问:
Critique the Structure of my Horse Racing Betting Platform
I am creating a program (mostly just for fun) that displays live prices for horse racing markets and the prices that several models predict they should be. I am very interested in the optimal way to structure this kind of data.

I need a Dictionary<int, (something)> to store <raceId, data> where the key (raceId) is a number I generate (to get rid of old races from the dictionary when the race is over). The vales (data) consists of the actual prices for each selection in the race and the prices of 3 separate models that correspond to each selection.

The dictionary will contain 20-60 races depending on the time.

Here is an example of the data for each race:

```<code>ActualPrice    ModelAPrice    ModelBPrice    ModelCPrice
3.25           3.26           3.29           3.20
5.60           5.63           5.55           5.57
etc.
</code>```

The number of rows is usually around 40. Some of the models don't offer prices for some of the rows, but for each actual price there is at least 1 model price.

Additionally, for each race data I store strings for the RaceCourse, StartTime, Location, etc. I also store marketIds in the form of ints, these correspond to several rows at a time (these are used to place the actual bets), there are about 6 marketIds per race.

I was using a class to store all the data in called RaceData that is made up of fields for strings (i.e. RaceCourse, Location), ints (i.e. WinMarketId, PlaceMarketId) and doubles (i.e. HorseA_ActualPrice, HorseA_ModelAPrice, etc). So my dictionary is made up of <RaceId, RaceData>.

But I was wondering if instead it would be better to store the data over 3 Dictionaries.

```<code>Dictionary<int, Dictionary<string, string>>
<RaceId, <StringName, StringValue>>
Example of usage: Use RaceId=102313 and StringName="RaceCourse" to get Value="Flemington"

Dictionary<int, Dictionary<string, int>>
<RaceId, <MarketName, MarketId>>
Example of usage: Use RaceId=131231 and MarketName="WinMarket" to get MarketId=1321313

Dictionary<int, Dictionary<string, double>[]>
An array of dictionaries (one for each column of the data).
<RaceId, <RowName, Price>>
Example of usage: Use RaceId=12313 and RowName="HorseAWinPrice" to get Price=3.25
</code>```

I'm not really sure if an array of dictionaries is needed for the last one, as I could just change the keys to have the column at the front, i.e. "ModelA_HorseBWinPrice" or "Actual_HorseBWinPrice". Which one is better?

Speed is a major concern when I have ~60 races and ~200 primatives for each. I have to perform several basic calculations using the values in each row for all of the races. I also need to display the racename/time in a listbox, and for the selected item in the listbox, display all of the prices on the form (in several list boxes). It is worth noting that each listbox corresponds to a marketId.

Which is a better solution or can you suggest a better one that I have not put forward?

答: Rather than using dictionaries I like the approach of using collections of classes for the different types. That would make the data more self-defining as well as allowing the use of LINQ to Objects to help aggregate and sort data.  It will also make it more straightforward to bind to the list boxes.</p>

ContentLicense: CC BY-SA 3.0


问:
Gradual Typing: "Almost every language with a static type system also has a dynamic type system"
This claim by Aleks Bromfield states:

Almost every language with a static type system also has a dynamic type system. Aside from C, I can't think of an exception

Is this a valid claim? I understand that with Reflection or Loading classes at runtime Java gets a bit like this - but can this idea of 'gradual typing' be extended to a large number of languages?

答:
Original tweeter here. :)

First of all, I'm somewhat amused/shocked that my tweet is being taken so seriously! If I had known it was going to be this widely disseminated, I would have spent more than 30 seconds writing it!

Thiago Silva is correct to point out that "static" and "dynamic" more accurately describe type checking, rather than type systems. In fact, it isn't really accurate to say that a language is statically or dynamically typed, either. Rather, a language has a type system, and an implementation of that language might enforce the type system using static checking, or dynamic checking, or both, or neither (though that would not be a very appealing language implementation!).

As it happens, there are certain type systems (or features of type systems) which are more amenable to static checking, and there are certain type systems (or features of type systems) which are more amenable to dynamic checking. For example, if your language allows you to specify in the text of a program that a particular value must always be an array of integers, then it's reasonably straightforward to write a static checker to verify that property. Conversely, if your language has subtyping, and if it permits downcasting, then it's reasonably straightforward to check the validity of a downcast at runtime, but extremely difficult to do so at compile time.

What I really meant by my tweet is simply that the vast majority of language implementations perform some amount of dynamic type checking. Or, equivalently, the vast majority of languages have some features that are difficult (if not impossible) to check statically. Downcasting is one example. Other examples include arithmetic overflow, array bounds checking, and null checking. Some of these can be statically checked in some circumstances, but by and large, you'd be hard-pressed to find a language implementation that doesn't do any checking at runtime.

This is not a bad thing. It's just an observation that there are many interesting properties that we would like our languages to enforce, and that we don't really know how to check statically. And it's a reminder that distinctions like "static types" versus "dynamic types" are not nearly as clear-cut as some people would have you believe. :)

One final note: the terms "strong" and "weak" aren't really used in the programming language research community, and they don't really have a consistent meaning. In general, I've found that when someone says that a language has "strong typing" and some other language has "weak typing", they're really saying that their favorite language (the one with "strong typing") prevents them from making some mistake that the other language (the one with "weak typing") doesn't -- or conversely, that their favorite language (the one with "weak typing") allows them to do some cool thing that the other language (the one with "strong typing") does not.


问:
How to prevent re-checking already-checked data?
I have a class with a validId($id) method that is called by the constructor and by public function load($id). The method queries the database to see if the id exists and returns true/false.

The constructor optionally takes an $id (if no $id, then the object will be empty).

The constructor checks the $id with validId($id), and if it passes, then it calls load($id).

I should not take validId() out of load() because load() is public and the input has to be checked!

The same goes for the constructor.

How do I avoid calling validId() twice? I was thinking I could add a parameter to load($id,$check_id), but that would be ridiculous. You can't give clients the option to not validate data!

I could add a protected property like $id_is_valid that gets set to true by validId($id). But how do I know the value that was valid is the same one being received by my load() method?

I'm using PHP.

Hopefully this isn't a stupid question.

答:
If the constructor calls load($id) (which calls validId by itself), why does it has to call validId first? Let it call load($id) unconditionally, make sure load($id) returns some status to show if the id was valid or not, so the constructor can act accordingly.

This suggestion will work, but it is still not the cleanest one. Better create an additional, private method load_unchecked($id) and call this from the constructor as well as from load. This gives you the control you want.


答:
But I was wondering if instead it would be better to store the data over 3
  Dictionaries.

Short answer: no, that is not better - it is worse and will lead you directly into a maintenance hell. Don't replace well names, well structured data by anonymous data which is distributed over different containers though it obviously belongs together.

Speed is a major concern when I have ~60 races and ~200 primatives for each.

I don't know your actual calculations, but I guess you won't notice a big performance difference between those two alternatives. So choose the cleaner one (which is clearly the first).

Title: Critique the Structure of my Horse Racing Betting Platform

Body:
I am creating a program (mostly just for fun) that displays live prices for horse racing markets and the prices that several models predict they should be. I am very interested in the optimal way to structure this kind of data.

I need a Dictionary<int, (something)> to store <raceId, data> where the key (raceId) is a number I generate (to get rid of old races from the dictionary when the race is over). The vales (data) consists of the actual prices for each selection in the race and the prices of 3 separate models that correspond to each selection.

The dictionary will contain 20-60 races depending on the time.

Here is an example of the data for each race:

```<code>ActualPrice    ModelAPrice    ModelBPrice    ModelCPrice
3.25           3.26           3.29           3.20
5.60           5.63           5.55           5.57
etc.
</code>```

The number of rows is usually around 40. Some of the models don't offer prices for some of the rows, but for each actual price there is at least 1 model price.

Additionally, for each race data I store strings for the RaceCourse, StartTime, Location, etc. I also store marketIds in the form of ints, these correspond to several rows at a time (these are used to place the actual bets), there are about 6 marketIds per race.

I was using a class to store all the data in called RaceData that is made up of fields for strings (i.e. RaceCourse, Location), ints (i.e. WinMarketId, PlaceMarketId) and doubles (i.e. HorseA_ActualPrice, HorseA_ModelAPrice, etc). So my dictionary is made up of <RaceId, RaceData>.

But I was wondering if instead it would be better to store the data over 3 Dictionaries.

```<code>Dictionary<int, Dictionary<string, string>>
<RaceId, <StringName, StringValue>>
Example of usage: Use RaceId=102313 and StringName="RaceCourse" to get Value="Flemington"

Dictionary<int, Dictionary<string, int>>
<RaceId, <MarketName, MarketId>>
Example of usage: Use RaceId=131231 and MarketName="WinMarket" to get MarketId=1321313

Dictionary<int, Dictionary<string, double>[]>
An array of dictionaries (one for each column of the data).
<RaceId, <RowName, Price>>
Example of usage: Use RaceId=12313 and RowName="HorseAWinPrice" to get Price=3.25
</code>```

I'm not really sure if an array of dictionaries is needed for the last one, as I could just change the keys to have the column at the front, i.e. "ModelA_HorseBWinPrice" or "Actual_HorseBWinPrice". Which one is better?

Speed is a major concern when I have ~60 races and ~200 primatives for each. I have to perform several basic calculations using the values in each row for all of the races. I also need to display the racename/time in a listbox, and for the selected item in the listbox, display all of the prices on the form (in several list boxes). It is worth noting that each listbox corresponds to a marketId.

Which is a better solution or can you suggest a better one that I have not put forward?


问:
How should you cleanly restrict object property types and values in Python?
I have been learning python from no long time ago. But nearly at the beginning I stumbled on simple question:
how to set a restriction (limitation) on object value or object's properties without making a difficult class description. There is no problem with python's unstrict typification. I search for the methods to control not only the variable types, but the variable value diapasons also. For example let creating the classical educational class - "Circle". A Circle - object should have three properties: two origin coordinates (some x, y) and a radius, in that (in our human visible world) x and  y should be real numerical, a radius should be real positive numerical.
I somehow solved this task, correspnding method of "Circle" class below:

```<code>def __setattr__(self,name,value):
    def setting_atr(name,value):
        if isinstance(value,(float,int)):
            if name=='radius' and value<0:
                raise ValueError("Attribute 'radius' should be no negative")
            self.__dict__[name]=value
        else:
            raise TypeError("Attribute should be numerical")
    if len(self.__dict__)<3: #number of object attribute
        return setting_atr(name,value)
    elif name not in self.__dict__:
        raise AttributeError("'Circle' object has no such attribute")
    else:
        return setting_atr(name,value)
</code>```

Nevertheless I utterly displeased with way I have done that. The code is huge for so small conception, and it's almost no reusable (I know about the descriptors - it will give the near same result). I would prefer some declarative stile. When I had been starting search for an alternative my first thought was to add my own operator. But after hard googling I realized that it impossible to make that in python itself (if I'm still wrong - please correst me). Such as I only newbie, and entering in python developers team or forked python ( :)) is no way for me, I gave up for this thoughts.
The another possibly path in declarative stile is writing something like:

```<code>radius=radius if isinstance(radius,(float,int)) else raise TypeError("Attribute should be numerical")
radius=radius if radius>=0 else raise ValueError("Attribute 'radius' should be no negative")
</code>```

of course it not work, because we haven't ability to use 'raise' by that. I should be able calling errors object as function to brought it for reality. The simplest way to do that it wrote the error-raised function like this:

```<code>def SomeError(exception=Exception, message="Something don't well"):
if isinstance(exception.args,tuple):
    raise exception
else:
    raise exception(message)
</code>```

So it allow to write:

```<code>radius=radius if radius>=0 else SomeError(ValueError("Attribute 'radius' should be no negative"))
</code>```

I also thought about followed form:

```<code>@dfValueError(['isinstance(radius,(float,int))'],"Attribute should be numerical")
@dfTypeError(['radius>=0'],"Attribute 'radius' should be no negative")
def fun_radius(x)
    return x
</code>```

The small problem with this approach is in the more complex and less informatively evident error outing print. At the first the error message lead to the fake error raised function, the place where "oops" actually occurred only in second lines.

My goal is to make possibility raise exception from lambda functions and code lines like has showed above, to make code more evident. To do this I should create my own exceptions class with call method implemented.
Problem: inherited class didn't see itself in own name spase, so method

```<code>__call__(self):
    raise self #yes ha-ha
</code>```

give in result:

```<code>TypeError: __call__() missing 1 required positional argument: 'self'
</code>```

So my question is simple:
is it possible to make error object be callable? If yes, what I should read, to do it. And also, if someone solve this small problem, I would be happy.
P.S. I know samples (about radius variable declaration) showed above can't be implemented in this "circle" class as is. I give it only as example to show my thoughts track. Please, don't pick on it.

Afterword (by Marat)
Thank very much who wrote and voted in this topic.
After readed answers, I thought very long, and finaly raised myself to add some augment
to this topic (even if it entail some risk to infringe rules).
For the first. Some people have wrote that we dont't need care about errors at the object creation state, and even no need to control variable types at all (inasmuch as it no has implemented in python by default). Although I have been no long time in object oriented programming, before that I had (and still have) been work on calculation a technical processes and devices. So I'm very confident about this words: "Possible error should be localized as soon as possible (I didn't say improved)". Many algorithms for calculation a real  physical processes use iterations and recursions so if you slip out (for later handle) some occurred mistake it could brought a hard detectable error in final result.
So, there is python, from this point of view. Python's "Duck Typing" is great for quick prototyping and simplifying applied programming. But "Duck Typing" is not a religion demand. Nevertheless Python's unstrict typification it isn't a bizarre thing to add a type control, if you think you need that. But the style which Python impose to perform it differ from the style in the static typification languages as C++, Java and etc. In Python we can control the object only in some "control points". This guide us to the "System Oriented Programming" principles (Therm is mine, but I didn't check if it exist in press, so it may has differ meaning from the same of another authors, and what I mean may also has another name).  We should (if will) set the "control points" at the inlet and outlet of the elements of (main) system. What is for the system elements? It should be any object who has own name space and can interact with outside as function (by methods also).
The simplest version of inlet controlling for function element is:

```<code>def func(a,b,c):
    #just like this
    a=int(a)
    b=str(b)
    c=list(c)
</code>```

More comlexity and interesting approach shown here:
Type-checking decorator for Python 2

Separately, about method that was suggested by my co-author. "Property" decorator use the same methods as descriptor, so it emulate object attributes by class methods. This mode should be used carefully because in python the objects of same class are shared the
class name space. I let myself rewrote the same programm that have wrote by @Izkata with __setattr__ (again):

```<code>filter_function_for_radius=lambda value: value if value>0 else SomeError(ValueError, 'Radius cannot be negative')
class Circle(object):
    def __init__(self, x=0, y=0, radius=1):
        self.x = x
        self.y = y
        self.radius =radius
    def __setattr__(self,name,value):
        if name=='radius':
            value=filter_function_for_radius(value)
        self.__dict__[name]=value
</code>```

...and if you need some another (perhaps complex or negative) radius for some hipothetical circle you don't need to inherit or redefine the class, just "change filter". But that advantage of function style may be obtain only by using __setattr__  or by creating own metaclass.
And once more thank you, for answering.

答:
THe trick is to try to not code too defensively. Try coding the minimum at first, maybe something like:

```<code>from collections import namedtuple
Circle = namedtuple('Circle', 'x, y, r')
c1 = Circle(0.0, 0.0, 1.0)
</code>```

Leave it up to users of Circle to provide reasonable values - it usually works.

The docstring of class Circle above is fixed and pretty terse as it just says:

```<code>'Circle(x, y, r)'
</code>```

You can make things clearer by, for example using more descriptive names:

```<code>Circle = namedtuple('Circle', 'center_x, center_y, radius')
</code>```

Or by sub-classing and adding a more extensive docstring:

```<code>class Circle(namedtuple('Circle', 'x, y, r')):
    '''\
    Circle(x, y, r): Circle centered at point x,y of radius r
    '''
</code>```

You need to ask yourself if you really need extensive type checking. It is normally not the first thing done when writing Python, and can seem counter-intuitive to programmers used to other programming languages.

Body:
THe trick is to try to not code too defensively. Try coding the minimum at first, maybe something like:

from collections import namedtuple
Circle = namedtuple('Circle', 'x, y, r')
c1 = Circle(0.0, 0.0, 1.0)

Leave it up to users of Circle to provide reasonable values - it usually works.

The docstring of class Circle above is fixed and pretty terse as it just says:

'Circle(x, y, r)'

You can make things clearer by, for example using more descriptive names:

Circle = namedtuple('Circle', 'center_x, center_y, radius')

Or by sub-classing and adding a more extensive docstring:

class Circle(namedtuple('Circle', 'x, y, r')):
    '''\
    Circle(x, y, r): Circle centered at point x,y of radius r
    '''

You need to ask yourself if you really need extensive type checking. It is normally not the first thing done when writing Python, and can seem counter-intuitive to programmers used to other programming languages.


问:
Breaking the "ubiquitous language" by having an IoC Container in Domain Model?
I am a bit new to DDD and bear with me if my understanding seems way off.

My question is about Udi's solution to domain events, particularly the class DomainEvents (see code below)

An excerpt from Udi's code. It lives domain model as a static class.

```<code>public static class DomainEvents
{
   [ThreadStatic] //so that each thread has its own callbacks
   private static List<Delegate> actions;

   public static IContainer Container { get; set; } //as before

   //Registers a callback for the given domain event
   public static void Register<T>(Action<T> callback) where T : IDomainEvent
   {
      if (actions == null)
         actions = new List<Delegate>();

      actions.Add(callback);
  }

  //Clears callbacks passed to Register on the current thread
  public static void ClearCallbacks ()
  {
      actions = null;
  }

  //Raises the given domain event
  public static void Raise<T>(T args) where T : IDomainEvent
  {
     if (Container != null)
        foreach(var handler in Container.ResolveAll<Handles<T>>())
           handler.Handle(args);

     if (actions != null)
         foreach (var action in actions)
             if (action is Action<T>)
                 ((Action<T>)action)(args);
  }
}
</code>```

Based on the code above, in order for the DomainEvents to be used by the domain model, both must first be in the same assembly. Which makes the DomainEvents part of the domain model right? (I may be wrong here)

So my question is: Does DomainEvents itself breaks the rule "ubiquitous language of DDD"? Because it's implementation does not pertain to any domain.

My other concern is that the static member IContainer creates an ioc-container-dependency in the domain model. Though I am not really sure if Udi's IContainer is an interface or an actual IoC container.

My 2nd question is: What is this IContainer in the DomainEvents class? If it is truly an IoC container then doesn't it break the rule of "DDD should not have an infrastructure in the domain"? Is my understanding correct that an IoC-Container is considered an infrastructure? (Please correct me if I'm wrong)

If you may find any of this confusing, please say so.

EDIT:

I have built my projects where the domain model is separated on its own assembly (I call this business layer) with absolutely no references to any infrastructure components. See onion architecture.

Now I want to incorporate the domain events pattern. But doing so forces me to add infrastructure components to my business layer. Components being the DomainEvents and an IoC framework just to satisfy the IContainer, both having no relation to the domain whatsoever.

Isn't one of the idea of DDD is about separating the infrastructure from the domain?

Now I will play the pragmatic programmer, I just wanted to know that is it generally ok to do so? are there alternatives? What are you thoughts on this approach? Am I missing something basic here?

答:
The idea of some kind of Publish-Subscribe within domain is not bad. It might be good abstraction that within domain, some events happen and others can react to them. And some kind of mediator exists, allows loose coupling between publishers and subscribers. So within ubiquitous language, there can be "entity X subscribes to events of type Y and will do Z" and "entity X publishes event of type Y when Z happens". This answers your first question.

But the implementation is wrong. There should be some kind of service, that mediates between the publishers and subscribers. And within domain, the service will be represented by an interface. The actual implementation of the interface will be inside the infrastructure. This way, there is no need for any container in the domain, because container is part of the implementation. And this answers your second question.

For example, in your code, you are creating dependence of your domain on IoC container. But IoC is part of infrastructure, so the dependency is the wrong way. By adding an interface in between, you can correct the direction of the dependency and put the implementation into infrastructure, where it belongs.


答:
I agree with you for the first sub-question:

From my point of view the class DomainEvents is infrasturcure code that should not be implemented in the domain itself.

So instead of a static class DomainEvents in the domain layer i would prefer a nonstatic class DomainEvents in an infrastructure layer that implements
an IEventHandling interface (in the domain layer) with methods Register, Raise, ...

The ioc container injets the implementation of IEventHandling as singleton to every class that needs DomainEvents.

```<code> > My 2nd question is: What is this IContainer in the DomainEvents class?
</code>```

The IOC-Container is infrastructure code so it is hidden behind an interface.

From architectual point of view i prefer referecing the ioc container only in one initialisation module and nowhere else. Therefore the icontainer should not be referenced from the class DomainEvents. Instead i would prefer to have a method DomainEvents.RegisterHandler and i would rename DomainEvents.Register to DomainEvents.RegisterEvent.

The ioc container initialisation module is repsonsible to register all handlers.

Title: Breaking the "ubiquitous language" by having an IoC Container in Domain Model?

Body:
I am a bit new to DDD and bear with me if my understanding seems way off.

My question is about Udi's solution to domain events, particularly the class DomainEvents (see code below)

An excerpt from Udi's code. It lives domain model as a static class.

```<code>public static class DomainEvents
{
   [ThreadStatic] //so that each thread has its own callbacks
   private static List<Delegate> actions;

   public static IContainer Container { get; set; } //as before

   //Registers a callback for the given domain event
   public static void Register<T>(Action<T> callback) where T : IDomainEvent
   {
      if (actions == null)
         actions = new List<Delegate>();

      actions.Add(callback);
  }

  //Clears callbacks passed to Register on the current thread
  public static void ClearCallbacks ()
  {
      actions = null;
  }

  //Raises the given domain event
  public static void Raise<T>(T args) where T : IDomainEvent
  {
     if (Container != null)
        foreach(var handler in Container.ResolveAll<Handles<T>>())
           handler.Handle(args);

     if (actions != null)
         foreach (var action in actions)
             if (action is Action<T>)
                 ((Action<T>)action)(args);
  }
}
</code>```

Based on the code above, in order for the DomainEvents to be used by the domain model, both must first be in the same assembly. Which makes the DomainEvents part of the domain model right? (I may be wrong here)

So my question is: Does DomainEvents itself breaks the rule "ubiquitous language of DDD"? Because it's implementation does not pertain to any domain.

My other concern is that the static member IContainer creates an ioc-container-dependency in the domain model. Though I am not really sure if Udi's IContainer is an interface or an actual IoC container.

My 2nd question is: What is this IContainer in the DomainEvents class? If it is truly an IoC container then doesn't it break the rule of "DDD should not have an infrastructure in the domain"? Is my understanding correct that an IoC-Container is considered an infrastructure? (Please correct me if I'm wrong)

If you may find any of this confusing, please say so.

EDIT:

I have built my projects where the domain model is separated on its own assembly (I call this business layer) with absolutely no references to any infrastructure components. See onion architecture.

Now I want to incorporate the domain events pattern. But doing so forces me to add infrastructure components to my business layer. Components being the DomainEvents and an IoC framework just to satisfy the IContainer, both having no relation to the domain whatsoever.

Isn't one of the idea of DDD is about separating the infrastructure from the domain?

Now I will play the pragmatic programmer, I just wanted to know that is it generally ok to do so? are there alternatives? What are you thoughts on this approach? Am I missing something basic here?

Body:
I agree with you for the first sub-question:

From my point of view the class DomainEvents is infrasturcure code that should not be implemented in the domain itself.

So instead of a static class DomainEvents in the domain layer i would prefer a nonstatic class DomainEvents in an infrastructure layer that implements
an IEventHandling interface (in the domain layer) with methods Register, Raise, ...

The ioc container injets the implementation of IEventHandling as singleton to every class that needs DomainEvents.

 > My 2nd question is: What is this IContainer in the DomainEvents class?

The IOC-Container is infrastructure code so it is hidden behind an interface.

From architectual point of view i prefer referecing the ioc container only in one initialisation module and nowhere else. Therefore the icontainer should not be referenced from the class DomainEvents. Instead i would prefer to have a method DomainEvents.RegisterHandler and i would rename DomainEvents.Register to DomainEvents.RegisterEvent.

The ioc container initialisation module is repsonsible to register all handlers.


问:
Why execution time is different each time in java?
I am trying to make a program in Java which measure the complexity of a specific program with respect to its run time. Let's take a problem and code that problem in all possible ways with respect to time complexity, let's say we can write code for a specific problem in O(n), O(log(n)), O(n log(n)) and O(n^2).

I will record the run time of each case and I will make a scale with these values to measure the time complexity of other's solution. Like

O(n) -> 2-3 ms

O(log(n)) -> 1-2 ms etc.

Now if other code has run time 2.3 ms, then my Java program will say that given solution has time complexity of the order O(n).

Now problem is that, as my code is in Java, whenever I run any program using Ubuntu commands  through Java code , each time I get the different run time, and the run time has very huge range from 0.364246 to  0.902362.

Why it is happening and what can I do to make a efficient scale?

Here is my code:

```<code>import java.io.*;

class ps_ef
{
    public static void main(String args[])
{
    String s=null,file_name,extension;
    int pos = args[0].lastIndexOf(".");

    extension = args[0].substring(pos+1);
    file_name = args[0].substring(0,pos);

    int lang = 0; //  1 -> c,c++ , 2 -> java

    try
    {

        Process compile = null;

        switch(extension)
        {
            case "c"    :    compile = Runtime.getRuntime().exec("gcc -g "+ args[0] + " -o "+file_name);
                        lang = 1;
                        break;
            case "c++"  :    compile = Runtime.getRuntime().exec("g++ -g "+ args[0] + " -o "+file_name);
                        lang = 1;
                        break;
            case "java" :    compile = Runtime.getRuntime().exec("javac "+ args[0]);
                        lang = 2;
        }

        BufferedReader stdError = new BufferedReader(new InputStreamReader(compile.getErrorStream()));

        if((s = stdError.readLine()) != null)
        {
            System.out.println("Compile Time Error OR Warning : ");

            System.out.println(s);
            while((s = stdError.readLine()) != null)
            {
                System.out.println(s);
            }
        }

        double startTime, run_time;
        Process run;

        if(lang == 1)
        {
             startTime = System.nanoTime();

             run = Runtime.getRuntime().exec("./"+file_name);

             run_time = (System.nanoTime()-startTime)/(double)Math.pow(10,6);
        }
        else
        {

            startTime = System.nanoTime();

             run = Runtime.getRuntime().exec("java "+file_name);

             run_time = (System.nanoTime()-startTime)/(double)Math.pow(10,6);
        }

        System.out.println("RunTime : "+ run_time+" ms");

        BufferedReader run_stdInput = new BufferedReader(new InputStreamReader(run.getInputStream()));

        BufferedReader run_stdError = new BufferedReader(new InputStreamReader(run.getErrorStream()));

        if(( s = run_stdError.readLine()) != null)
        {
            System.out.println("Runtime Error : ");

            System.out.println(s);

            while((s = run_stdError.readLine()) != null )
            {
                System.out.println(s);
            }
        }
        else if((s = run_stdInput.readLine()) != null)
        {
            String s_string = null;
            int failed = 0;

            File fs = new File(file_name+".txt");

            BufferedReader br  = new BufferedReader(new FileReader(fs));

            if((!s.equals(s_string = br.readLine())))
            {
                failed = 1;
            }

            while(((s = run_stdInput.readLine()) != null) & ((s_string = br.readLine()) != null) & (failed == 0))
            {
                if(!s.equals(s_string) )
                {
                    failed = 1;
                    break;
                }
            }

            if((failed == 1) || s != null || s_string != null)
            {
                System.out.println("Submmision Failed : ");
                System.out.println("Either Output Is Wrong.\nOR\nYour Output Is Not According To The Given Format. ");
                System.exit(0);

            }
            else
            {
                System.out.println("Submission Successful.");
            }

        }
    }
    catch(IOException e)
    {
        System.out.println("Some Error Has Occured : ");
        e.printStackTrace();
        System.exit(-1);
    }

}
</code>```

}

Here is my output of run time:

答:
Benchmarking is a difficult science. It seems that your computer is conspiring against you:

Your CPU keeps often-requested data in caches. As accessing  memory in a cache is faster than using other memory, this can warp benchmarks.

Your OS may cache files in memory rather than loading them from disk. Obviously this hasn't happened the first time you run a program. Subsequent runs should be faster.

Time-sharing operating system kernels like Linux, Mach or Windows NT juggle multiple processes at the same time. This means that other processes may be executed in between of execution phases of your benchmarked program. Therefore measuring the elapsed time is inaccurate (it likely also includes execution time from other processes). You should be measuring the used CPU time instead. On the other hand that become inaccurate if the benchmark isn't CPU-bound.

Measuring elapsed time vs. CPU time is also important when considering multi-threaded programs that run on multiple cores. A multi-threaded program can run “faster”, but use more CPU time than a single-threaded solution.

Scheduling not only affects how the times should be measured, but can also invalidate caches.

Benchmarking programs written on the JVM is even more complicated because

It has a massive start-up time that has to be subtracted to get the actual run time

It may interpret the program (slow) or compile it to highly optimized machine code (takes a moment, then extremely fast), or may revert back to interpreting. So while for many uses, Java is slower than C, it can potentially be faster.

Garbage collection may halt the execution at any time to analyze the memory.

There are many settings that can affect JVM performance; doing this correctly is difficult.

Now let's say you have figured out how to obtain correct measurements. We can then solve issues around file caching by simply running the program multiple times and discarding the first run. Issues around scheduling can be minimized by running the benchmarks in a controlled environment with few processes (e.g. running in single-user mode without a graphical environment).

We can now collect a series of data points for each program. Especially on the JVM it is important to run the code repeatedly until all optimizations have kicked in so that the measurements have roughly converged onto one level. An useful tool for this is the mean value of the last n measurements.

When reporting the average run time, we not only report the mean value of all runs, but also the standard deviation (sometimes called sigma) that shows how coherent the measurements are. A smaller value is preferable. The SD is normalized on the mean value, so it is only comparable for the same mean value, not between runs with different means.

If you want to show that a program has a specific algorithmic time complexity, you have to run it with inputs of different sizes (e.g. n = 0, …, 1.000.000 items in steps of 100.000). For each input size you will record one or more measurements, and then fit different equations to the data set:

```<code>O(1):       t = a
O(log n):   t = a * log(n)/log(b) + c    likely special cases a=2 or a=e
O(n):       t = a * n   + b
O(n log n): t = a * n * log(n)/log(b) + c
O(n^2):     t = a * n^2 + b
O(n^3):     t = a * n^3 + b
O(a^n):     t = a^(b * n) * c + d    likely special case of a=2
...
</code>```

For each fit, you can then calculate the square distance between the fit and the data set. The complexity class with the smallest square distance to the data set is probably the complexity class of the used algorithm.

Implementing curve fitting yourself is almost as non-trivial as correct benchmarking, so you should probably use an existing implementation (I use Python with scipy for this kind of work).

Note that in complex cases the observed run time can be the sum of run times of algorithms with different complexities, but the largest complexity class should dominate on sufficiently large input.

Body:
Benchmarking is a difficult science. It seems that your computer is conspiring against you:

Your CPU keeps often-requested data in caches. As accessing  memory in a cache is faster than using other memory, this can warp benchmarks.

Your OS may cache files in memory rather than loading them from disk. Obviously this hasn't happened the first time you run a program. Subsequent runs should be faster.

Time-sharing operating system kernels like Linux, Mach or Windows NT juggle multiple processes at the same time. This means that other processes may be executed in between of execution phases of your benchmarked program. Therefore measuring the elapsed time is inaccurate (it likely also includes execution time from other processes). You should be measuring the used CPU time instead. On the other hand that become inaccurate if the benchmark isn't CPU-bound.

Measuring elapsed time vs. CPU time is also important when considering multi-threaded programs that run on multiple cores. A multi-threaded program can run “faster”, but use more CPU time than a single-threaded solution.

Scheduling not only affects how the times should be measured, but can also invalidate caches.

Benchmarking programs written on the JVM is even more complicated because

It has a massive start-up time that has to be subtracted to get the actual run time

It may interpret the program (slow) or compile it to highly optimized machine code (takes a moment, then extremely fast), or may revert back to interpreting. So while for many uses, Java is slower than C, it can potentially be faster.

Garbage collection may halt the execution at any time to analyze the memory.

There are many settings that can affect JVM performance; doing this correctly is difficult.

Now let's say you have figured out how to obtain correct measurements. We can then solve issues around file caching by simply running the program multiple times and discarding the first run. Issues around scheduling can be minimized by running the benchmarks in a controlled environment with few processes (e.g. running in single-user mode without a graphical environment).

We can now collect a series of data points for each program. Especially on the JVM it is important to run the code repeatedly until all optimizations have kicked in so that the measurements have roughly converged onto one level. An useful tool for this is the mean value of the last n measurements.

When reporting the average run time, we not only report the mean value of all runs, but also the standard deviation (sometimes called sigma) that shows how coherent the measurements are. A smaller value is preferable. The SD is normalized on the mean value, so it is only comparable for the same mean value, not between runs with different means.

If you want to show that a program has a specific algorithmic time complexity, you have to run it with inputs of different sizes (e.g. n = 0, …, 1.000.000 items in steps of 100.000). For each input size you will record one or more measurements, and then fit different equations to the data set:

O(1):       t = a
O(log n):   t = a * log(n)/log(b) + c    likely special cases a=2 or a=e
O(n):       t = a * n   + b
O(n log n): t = a * n * log(n)/log(b) + c
O(n^2):     t = a * n^2 + b
O(n^3):     t = a * n^3 + b
O(a^n):     t = a^(b * n) * c + d    likely special case of a=2
...

For each fit, you can then calculate the square distance between the fit and the data set. The complexity class with the smallest square distance to the data set is probably the complexity class of the used algorithm.

Implementing curve fitting yourself is almost as non-trivial as correct benchmarking, so you should probably use an existing implementation (I use Python with scipy for this kind of work).

Note that in complex cases the observed run time can be the sum of run times of algorithms with different complexities, but the largest complexity class should dominate on sufficiently large input.


问:
Testing Framework Selection: xUnit family theory
Background:

I am familiar with xUnit family frameworks and have had experience with (shunit2, PhpUnit and simpletest). I am currently trying to find a testing framework for C++. I did a quick search for frameworks using Wikipedia's list of documented frameworks; however, the framework I would like to use is very difficult to setup and is poorly documented. There is another framework that I have tried that was (IMHO) extremely easy to setup and integrate into my production workflow.

The difference between my framework of choice (the one that is difficult to setup) and the one that I'm currently using (the one that was easy to setup) is compliance with xUnit methodology.

Questions:

1. I have read quite a few articles about xUnit testing frameworks. I believe that they use similar naming conventions and testing methods for their test. Is this true and what are the naming methods utilized?

2. Does staying with xUnit testing frameworks make it easier to run integration tests when using multiple languages?

3. From a training perspective is it more cost effective to teach new programmers a set of tools based on the same concept or different individual tools that do the same thing?

I kept the frameworks that I am looking at anonymous because I am more interested in industry best practices than a comparison of the two said frameworks

答:
I've found that while a set of tools in the same family might sound like they should all be the same (specifically I'm thinking of log4x, which is an awesome log library and much better than things like the .net logging stuff) it is still different enough in its configuration and use to practically be separate tools.

So I would not stick with a single family of tooling, and would use whatever tool you liked best, regardless of its provenance.

I find this kind of thinking prevalent in the Microsoft world - "we use Microsoft here" and no matter how bad the Microsoft tool might be, or how wonderful the non-Microsoft tool is, some people will simply not use the good stuff, and will stick with whatever Microsoft gives them. (It used to be the same with IBM, and I'm sure other places have the same mindset). The problem here is that they restrict themselves to the idea that there is stuff out there that is actually better.

So use the tooling you think is best. If you (and everyone else) refused to use a non xUnit test framework then there would be little incentive for people to come up with new, better ways of solving the problem. Using the better quality product is industry best practice IMHO.


问:
Coworker that detrimentally picks on every minutia
Hypothetically speaking imagine that there exists a coworker that has a very shallow understanding of computing. To avoid stereotyping lets give this coworker the gender neutral name Chris.

Now Chris' diagnostic ability is low and can't figure out the correct IP addresses to set his/her virtual machines to. Chris also fails to merge code properly and overwrites a commit I made fixing something, thereby re-introducing a bug. I let this slide, refix the bug and do not make a sound about it to management.

Given a task Chris either 1) complains that there isn't sufficient information resulting in 2) you provide Chris with inordinately detailed instructions to satisfy 1). The more detail you provide in a list of steps to carry out, the more chance of an error being present in your instructions. Chris gets these instructions, tries to execute them, fails and it becomes your fault because your instructions aren't good enough. How do you deal with this?

答:
I think the point is not to program a robot colleague.

Provide sufficient but brief pointers. Ask him, what's missing if he complains.
Either his complain is fair, then you can give him more information or it is unfair and then you can document his incompetence (if you exchange the details via email).

ContentLicense: CC BY-SA 2.5


问:
Should db be mapped directly to the UI or should there be multiple layers of enties/models with mappings to/from each?
I would like to know arguments for/against this concept.

Technologies in use from the bottom up:

MSSQL 2012 DB (exclusively accessed via sprocs)

Entity Framework

WCF Web Service

ASP.NET Webforms

Someone on my team would like to use Entity Framework to map the sprocs to ComplexTypes, and then use those ComplexTypes as DTOs, eventually using them as a view model to display on the page.  His argument is that it's the fastest/easiest way and we'll get noticeable/valued changes more quickly.  Also, he does not like the idea of the numerous mappings that would be necessary to go from DB -> Entity -> DTO -> ViewModel.

Another consideration is, the majority of things from the DB are going one direction (db -> web), with only a few things actually needing to be changed on the UI and saved/persisted to the DB.

To scope this question, there are thousands of previously existing sprocs written against poorly designed database structure (think tables that are 276 columns wide and single rows actually contain multiple entities).  The poor structure isn't about to change soon because there are over 200 legacy apps written on top of it.

答:
Yukky database... well, given that exists then the first thing you need to do is only allow access to the DB via sprocs, effectively encapsulate the DB in its own API. Once you do this, it'll eventually be possible to replace/redesign it without any client knowing.

Sounds like you've already done this, so good so far.

Now, accessing that API can be done in any number of ways, and using EF to do this is a good RAD way of doing it, even if SQLClient will be faster - doesn't make too much difference all in all.

Mapping a sproc's results to a ComplexType is exactly what a ComplexType is designed for (don't try to use it as if it were an EF view of a DB). Its a temporary result type that does not map to the underlying table - its effectively a dynamically generated type that contains just the results from the sproc and has no relation to the actual DB structure.

However, the problem comes when you try to write these back to the DB - you have to tell EF that the data in the type maps onto a DB table (or it won't know what to do with it), and we are trying to remove the whole DB schema from the service code, accessing the DB through its sprocs only. If you have sprocs to write, then there's no reason you can't just unpick the individual elements of the type and pass them to the relevant sproc in the WCF service. In this case, you simply make it easier to code your service to client code as EF does the class creation for you. Of course, if you've already got such classes for the sproc then its not really going to help you much.

So I think its safe to say he's right, its a simple and worthwhile convenience mechanism that should work well for you - assuming you're not trying to subvert the sprocs, or have a similar mechanism in place. You might find issues with getting the definition of the types into all parts of your chain, depending on how it all gets compiled together, but that's a solveable problem. I would get him to knock up a PoC demonstrating how a new service would call a simple sproc and transfer the data to the client (no need to write the web code to go with it) and back again, and review that. I think you'll find that it does what you've already been doing in a way that means the compiler does a load of boring work for you.

As for reducing the need to go Entity->DTO->View... there's a lot of complexity in web MVC that was put there because Ruby on Rails did it that way, and everyone says MVC is a great way to split your code up. My personal view is that MVC inside the same layer is just over-engineering the problem (that might be good if you only have that layer talking to the DB, not if you already have a well designed 3-tier solution). If you already have a web service and DB layer accessed via sprocs then you've done it right already, no real need to replicate this architecture in the web server as well! So yes, I'd remove as much of the web view code to make it as simple as possible.


问:
Does condition coverage subsume edge coverage?
I'm a little bit confused about code coverage criteria; especially condition and edge coverage.

As stated in this book, edge coverage does not subsume condition coverage; BUT my lecture material defines condition coverage in the following way:

Edge Coverage Criterion: Select a test set T such that, by executing a program P for each d in T, each edge of P‘s control flow graph is traversed at least once

Condition Coverage Criterion: Select a test set T such that, by executing P for each element in T, each edge of P‘s control flow graph is traversed, and all possible values of the constituents of compound boolean conditions are exercised at least once.

So, the first part of the definition of condition coverage is obviously the same as the whole definition of edge coverage. Hence, I thought condition coverage implies edge coverage ...

Is the definition broken? What's correct?

答:
Based on your definitions, it looks like edge coverage does not imply condition coverage, but condition coverage does imply edge coverage. In other words, by covering all conditions, you will be guaranteed to cover every edge; but by covering every edge, you are not guaranteed to cover every condition.

For example,

```<code>int function(int arg1, int arg2)
{
    if(arg1 < 0 || arg2 < 0)
        return -1;
    else
        return arg1 + arg2;
}
</code>```

Going by edge coverage, the edges here are "return -1", and "return arg1 + arg2"; in order to cover both of those edges, you need only two invocations:

```<code>function(-1, 0); function(0, 0);
</code>```

There are, however, three conditions (considering the Boolean short-circuiting logic): arg1 < 0, arg1 >= 0 && arg2 < 0, and arg1 >= 0 && arg2 >= 0, so you'd need something like the following to achieve complete condition coverage:

```<code>function(-1, 0); function(0, -1); function(0, 0);
</code>```

The key distinction in the definitions you posted is "and all possible values of the constituents of compound boolean conditions are exercised at least once". Covering all the conditions will ensure that you will hit all the edges. But as you see, covering all the edges does not ensure that you will hit all the conditions.

Body:
Based on your definitions, it looks like edge coverage does not imply condition coverage, but condition coverage does imply edge coverage. In other words, by covering all conditions, you will be guaranteed to cover every edge; but by covering every edge, you are not guaranteed to cover every condition.

For example,

int function(int arg1, int arg2)
{
    if(arg1 < 0 || arg2 < 0)
        return -1;
    else
        return arg1 + arg2;
}

Going by edge coverage, the edges here are "return -1", and "return arg1 + arg2"; in order to cover both of those edges, you need only two invocations:

function(-1, 0); function(0, 0);

There are, however, three conditions (considering the Boolean short-circuiting logic): arg1 < 0, arg1 >= 0 && arg2 < 0, and arg1 >= 0 && arg2 >= 0, so you'd need something like the following to achieve complete condition coverage:

function(-1, 0); function(0, -1); function(0, 0);

The key distinction in the definitions you posted is "and all possible values of the constituents of compound boolean conditions are exercised at least once". Covering all the conditions will ensure that you will hit all the edges. But as you see, covering all the edges does not ensure that you will hit all the conditions.


问:
If every instance of a type is to be random, how should the Random generator object be stored?
It seems to me that this is often encountered in practice and I was wondering if there is a design pattern for the following:

Suppose I have a class that represents a card:

```<code>public class Hand {
    private static Random rng;
    private Rank rank;
    private Suit suit;
    public Hand() {
        if (prng == null)
            prng = new Random();
        }
        //more stuff
    }
}
</code>```

Every time I instantiate a Card, I want a random card. Doing it the above way wastes one comparison to null per instantiation.  If I create a static field and allocate it in the deceleration:

```<code>private static Random rng = new Random();
</code>```

a new Random object gets instantiated every time - also not very efficient.

If I pass the Random object into the constructor, I violate "tell, don't ask."

Perhaps there is another suggestion, but so far, I think the best way is the null check.

答:
If I create a static field and allocate it in the deceleration:

```<code>private static Random rng = new Random();
</code>```

a new Random object gets instantiated every time - also not very efficient.

This is simply not true - it will create a single Random when the class is initialized, that's what static means. Thus, it is the correct solution. But also note that  Random objects are pretty lightweight and there is no reason to be overly reluctant to create them, unless you're doing it millions of times per second.

Body:
If I create a static field and allocate it in the deceleration:

private static Random rng = new Random();

a new Random object gets instantiated every time - also not very efficient.

This is simply not true - it will create a single Random when the class is initialized, that's what static means. Thus, it is the correct solution. But also note that  Random objects are pretty lightweight and there is no reason to be overly reluctant to create them, unless you're doing it millions of times per second.


答:
A constructor should be deterministic if possible, otherwise your code will be untestable. Have at least one overloaded constructor that can accept an RNG:

```<code>public Hand(Random prng) {
  // more stuff
}
</code>```

An argument-less constructor could give a default RNG, as in your design sketch. While a null comparision isn't that expensive and a new Hand isn't that common, you could just initialize the RNG with the class:

```<code>private static Random prng = new Random();

public Hand() {
  this(prng);
}
</code>```

This way, the RNG initialization is executed only once.

Otherwise, the quote about premature optimization applies…

Title: If every instance of a type is to be random, how should the Random generator object be stored?

Body:
It seems to me that this is often encountered in practice and I was wondering if there is a design pattern for the following:

Suppose I have a class that represents a card:

```<code>public class Hand {
    private static Random rng;
    private Rank rank;
    private Suit suit;
    public Hand() {
        if (prng == null)
            prng = new Random();
        }
        //more stuff
    }
}
</code>```

Every time I instantiate a Card, I want a random card. Doing it the above way wastes one comparison to null per instantiation.  If I create a static field and allocate it in the deceleration:

```<code>private static Random rng = new Random();
</code>```

a new Random object gets instantiated every time - also not very efficient.

If I pass the Random object into the constructor, I violate "tell, don't ask."

Perhaps there is another suggestion, but so far, I think the best way is the null check.

Body:
A constructor should be deterministic if possible, otherwise your code will be untestable. Have at least one overloaded constructor that can accept an RNG:

public Hand(Random prng) {
  // more stuff
}

An argument-less constructor could give a default RNG, as in your design sketch. While a null comparision isn't that expensive and a new Hand isn't that common, you could just initialize the RNG with the class:

private static Random prng = new Random();

public Hand() {
  this(prng);
}

This way, the RNG initialization is executed only once.

Otherwise, the quote about premature optimization applies…


答:
Here is some code of mine without the TypeError: __call__() missing 1 required positional argument: 'self'. How do you create this error?

```<code>>>> class X(Exception):
    def __call__(self):
        raise self

>>> x = X()
>>> x()

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    x()
  File "<pyshell#3>", line 3, in __call__
    raise self
X
>>> class Other(X):
    pass

>>> o = Other()
>>> o()

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    o()
  File "<pyshell#3>", line 3, in __call__
    raise self
Other
</code>```

Title: How should you cleanly restrict object property types and values in Python?

Body:
I have been learning python from no long time ago. But nearly at the beginning I stumbled on simple question:
how to set a restriction (limitation) on object value or object's properties without making a difficult class description. There is no problem with python's unstrict typification. I search for the methods to control not only the variable types, but the variable value diapasons also. For example let creating the classical educational class - "Circle". A Circle - object should have three properties: two origin coordinates (some x, y) and a radius, in that (in our human visible world) x and  y should be real numerical, a radius should be real positive numerical.
I somehow solved this task, correspnding method of "Circle" class below:

```<code>def __setattr__(self,name,value):
    def setting_atr(name,value):
        if isinstance(value,(float,int)):
            if name=='radius' and value<0:
                raise ValueError("Attribute 'radius' should be no negative")
            self.__dict__[name]=value
        else:
            raise TypeError("Attribute should be numerical")
    if len(self.__dict__)<3: #number of object attribute
        return setting_atr(name,value)
    elif name not in self.__dict__:
        raise AttributeError("'Circle' object has no such attribute")
    else:
        return setting_atr(name,value)
</code>```

Nevertheless I utterly displeased with way I have done that. The code is huge for so small conception, and it's almost no reusable (I know about the descriptors - it will give the near same result). I would prefer some declarative stile. When I had been starting search for an alternative my first thought was to add my own operator. But after hard googling I realized that it impossible to make that in python itself (if I'm still wrong - please correst me). Such as I only newbie, and entering in python developers team or forked python ( :)) is no way for me, I gave up for this thoughts.
The another possibly path in declarative stile is writing something like:

```<code>radius=radius if isinstance(radius,(float,int)) else raise TypeError("Attribute should be numerical")
radius=radius if radius>=0 else raise ValueError("Attribute 'radius' should be no negative")
</code>```

of course it not work, because we haven't ability to use 'raise' by that. I should be able calling errors object as function to brought it for reality. The simplest way to do that it wrote the error-raised function like this:

```<code>def SomeError(exception=Exception, message="Something don't well"):
if isinstance(exception.args,tuple):
    raise exception
else:
    raise exception(message)
</code>```

So it allow to write:

```<code>radius=radius if radius>=0 else SomeError(ValueError("Attribute 'radius' should be no negative"))
</code>```

I also thought about followed form:

```<code>@dfValueError(['isinstance(radius,(float,int))'],"Attribute should be numerical")
@dfTypeError(['radius>=0'],"Attribute 'radius' should be no negative")
def fun_radius(x)
    return x
</code>```

The small problem with this approach is in the more complex and less informatively evident error outing print. At the first the error message lead to the fake error raised function, the place where "oops" actually occurred only in second lines.

My goal is to make possibility raise exception from lambda functions and code lines like has showed above, to make code more evident. To do this I should create my own exceptions class with call method implemented.
Problem: inherited class didn't see itself in own name spase, so method

```<code>__call__(self):
    raise self #yes ha-ha
</code>```

give in result:

```<code>TypeError: __call__() missing 1 required positional argument: 'self'
</code>```

So my question is simple:
is it possible to make error object be callable? If yes, what I should read, to do it. And also, if someone solve this small problem, I would be happy.
P.S. I know samples (about radius variable declaration) showed above can't be implemented in this "circle" class as is. I give it only as example to show my thoughts track. Please, don't pick on it.

Afterword (by Marat)
Thank very much who wrote and voted in this topic.
After readed answers, I thought very long, and finaly raised myself to add some augment
to this topic (even if it entail some risk to infringe rules).
For the first. Some people have wrote that we dont't need care about errors at the object creation state, and even no need to control variable types at all (inasmuch as it no has implemented in python by default). Although I have been no long time in object oriented programming, before that I had (and still have) been work on calculation a technical processes and devices. So I'm very confident about this words: "Possible error should be localized as soon as possible (I didn't say improved)". Many algorithms for calculation a real  physical processes use iterations and recursions so if you slip out (for later handle) some occurred mistake it could brought a hard detectable error in final result.
So, there is python, from this point of view. Python's "Duck Typing" is great for quick prototyping and simplifying applied programming. But "Duck Typing" is not a religion demand. Nevertheless Python's unstrict typification it isn't a bizarre thing to add a type control, if you think you need that. But the style which Python impose to perform it differ from the style in the static typification languages as C++, Java and etc. In Python we can control the object only in some "control points". This guide us to the "System Oriented Programming" principles (Therm is mine, but I didn't check if it exist in press, so it may has differ meaning from the same of another authors, and what I mean may also has another name).  We should (if will) set the "control points" at the inlet and outlet of the elements of (main) system. What is for the system elements? It should be any object who has own name space and can interact with outside as function (by methods also).
The simplest version of inlet controlling for function element is:

```<code>def func(a,b,c):
    #just like this
    a=int(a)
    b=str(b)
    c=list(c)
</code>```

More comlexity and interesting approach shown here:
Type-checking decorator for Python 2

Separately, about method that was suggested by my co-author. "Property" decorator use the same methods as descriptor, so it emulate object attributes by class methods. This mode should be used carefully because in python the objects of same class are shared the
class name space. I let myself rewrote the same programm that have wrote by @Izkata with __setattr__ (again):

```<code>filter_function_for_radius=lambda value: value if value>0 else SomeError(ValueError, 'Radius cannot be negative')
class Circle(object):
    def __init__(self, x=0, y=0, radius=1):
        self.x = x
        self.y = y
        self.radius =radius
    def __setattr__(self,name,value):
        if name=='radius':
            value=filter_function_for_radius(value)
        self.__dict__[name]=value
</code>```

...and if you need some another (perhaps complex or negative) radius for some hipothetical circle you don't need to inherit or redefine the class, just "change filter". But that advantage of function style may be obtain only by using __setattr__  or by creating own metaclass.
And once more thank you, for answering.

Body:
Here is some code of mine without the TypeError: __call__() missing 1 required positional argument: 'self'. How do you create this error?

>>> class X(Exception):
    def __call__(self):
        raise self

>>> x = X()
>>> x()

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    x()
  File "<pyshell#3>", line 3, in __call__
    raise self
X
>>> class Other(X):
    pass

>>> o = Other()
>>> o()

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    o()
  File "<pyshell#3>", line 3, in __call__
    raise self
Other


问:
What's the right way to fork/re-use code from an open source project?
Let's say I am working on an open source project and want to re-use a trivial utility function from another open source project (for example, a file search/replace function). Is it legal to copy the function and simply write a small copyright notice in top of the file? Should I include their name as copyright holders of the entire project in the license?

Similarly, let's say I fork an open source project. Where and how do I specify that the copyright is shared between both the original copyright holder and myself?

I guess the answer must somewhat vary according to the open source license but I'd like a general answer as much as possible.

PS: I'm mostly concerned about the legal aspect, but feel free to include your ethical point of view.

答:
I'm trying to make this answer as 'meta' applicable as possible.

Using snippets / bits from other projects

Clearly mark the code with the original author's copyright. Make sure that your license of choice is fully compatible with the license of the code you are using. You will need permission of the author to move the code to a different license (unless they specifically allow you to do so, I.e. "GPL 2 or any later version")

Your program should have an AUTHORS file (or similar), where you list all contributors and things that you used from other projects.

Forking a project

For each module that you substantially change, add your copyright under the original author's. The same thing goes for licensing, you are bound by the terms of the license that was in effect when you forked it. If the project says "GPL2 only", you must respect that, you can't go to GPL3 without their permission.

This varies, greatly, depending on the license at hand. The QPL says you can only distribute changes in patch format, for instance, so make sure you understand the terms that allow you to distribute modified versions of the software.

Beyond that, always preserve copyright. If adding your own copyright to what exists, be sure that you clearly mark exactly what you are claiming.


问:
Is there a guide for software development to design efficient hotkeys for actions?
I don't know how to word this easily but basically the software I am writing has a ton of actions and I want to assign hotkeys to every one of them so power users can work super fast.

First off they are not actions related to the application itself, i.e. Quit, Maximize Window, About, Preferences, etc. But rather actual operations you perform on the data set.

It's not exactly the same but closest example I can give is the Nuke compositor, where each action is represented by a node. So things like Blur, Sharpen, Add, Color Correction, Keylight, etc.

But since the number of nodes are over 500, I don't know how to create easy to remember hotkeys that do not use every modifier key combination.

Is using 2 key combo, i.e. CC for Color Correction the best way?

Are there resources on this subject? Basically maximizing the use of hotkeys to take working speed to the max without having to remember 1000s of key combinations.

答:
Don't Guess

Ask a few power-users what would be most convenient/efficient/memorable for them. Then user-test it and adjust.

(Making hotkeys soft-bindable is fine, but it doesn't answer the initial-configuration question; that is best answered by actual users)


答:
I'm not an expert in this area, but I'm fan of hotkey driven productivity and a frequent user of AutoHotkey.  I've thought on the subject quite a bit, and on numerous occasions I've run into challenges related to trying to come up with custom hotkeys that don't conflict with existing OS/Application hotkeys.

There must be resources out there on the subject, but honestly I haven't come across any deep research on hotkey thus far, aside from brief mentions with respect to usability.  I would echo what some of the commenters are saying with respect to the fact that hotkey assignment often falls under the broad umbrella of UX/Usability, so you might have better luck in another venue.

Regardless, a few thoughts that may help:

1.)  Most frequently used commands should have a low key-distance

By 'low key distance' I mean the distance you need to stretch a single hand in order to trigger a hotkey.  On the Windows platform a classic example is Ctrl + C (copy) and Ctrl + V (paste).  Because V falls within the left hemisphere of the keyboard, a user can use the mouse and the keyboard shortcuts simultaneously to great effect.

If you expect users of your software to be using a mouse at all times, consider everything past the G key on a standard US-QWERTY keyboard to be off-limits for high-frequency hotkeys.

2.)  Put hotkeys into logical groups

This goes without saying, use a logical hierarchy when assigning hotkeys.

3.) Develop a generalized strategy if you have a large number of hotkeys

You might be able to get away with a few hotkeys such as cc for color captioning, but I don't think it's advisable. An application with a need for many hotkeys most likely has many distinct operations which share a first letter.  Likewise, a same-letter hotkey would require you to have a wait-and-listen interval after every keypress, which is more likely to slow down and annoy a power user than help him.  Your strategy will have to depend upon what keys you can sacrifice for hotkey activation, how many combinations you need, and what feels intuitive.

A couple of strategies I've observed that seem to be effective.  (Both of them utilize hotkey tree traversal)

a.) Utilize chords -  Visual Studio uses multi-key chords for IDE hotkeys.  They don't always make a lot of sense, but the ones that do tend to follow a standard two-part convention.   ->

One good example of this is the 'refactor' chords:

Chord Root:  Ctrl + R

Chord Commands:
  - Encapsulate Field
  - Extract Interface
  - Extract Method
  - Remove Parameters
  - Rename
  - Reorder Parameters

The upside of this is that by forcing the initial keystroke of certain hotkeys to be a 'chord activation' you get significantly more hotkeys from the same effective area of the keyboard... The downside is that it's a bit confusing and with this scheme you may have more key presses overall, since the initial keystroke for many commands may be a chord activation.

b.)  Use context-aware hotkey traversal

In addition to the standard application-specific hotkeys, all of the more recent Microsoft Office applications have an interesting means of menu traversal activated by the Alt key.

A couple of images will make it easier to explain:

I open Word 2013, then press Alt, and I see the top level menu tree highlighted

From there, I press I and see the next layer of hotkeys highlighted

As you can see, this approach could potentially give you as many hotkeys as you want, provided you are willing to go a few layers down for certain hotkeys, you're willing to force the user to start at a specific root keypress.  I would say that this approach is better suited to extremely hierarchical  shortcuts, as opposed to the more ad-hoc chord approach.

Regardless of the approach you come up with, there will always be some sort of tradeoff between efficiency, complexity and ease of use.  The more complex you make the hotkey system, the more you will want to offset it with visual cues and reference documentation.

Lastly I don't know what you're building, but I would also take a good look at similar applications, to see what they are doing. Users often expect a similar hotkey scheme between applications in the same problem domain.  If there is already an application you'd consider the industry standard, consider adopting some of their hotkeys to ease the transition.

Hope this helps!

Title: Is there a guide for software development to design efficient hotkeys for actions?

Body:
I don't know how to word this easily but basically the software I am writing has a ton of actions and I want to assign hotkeys to every one of them so power users can work super fast.

First off they are not actions related to the application itself, i.e. Quit, Maximize Window, About, Preferences, etc. But rather actual operations you perform on the data set.

It's not exactly the same but closest example I can give is the Nuke compositor, where each action is represented by a node. So things like Blur, Sharpen, Add, Color Correction, Keylight, etc.

But since the number of nodes are over 500, I don't know how to create easy to remember hotkeys that do not use every modifier key combination.

Is using 2 key combo, i.e. CC for Color Correction the best way?

Are there resources on this subject? Basically maximizing the use of hotkeys to take working speed to the max without having to remember 1000s of key combinations.


问:
Should I use the new method/action to retrieve records? (Rails)
I have an admin controller that is just used for its index action which renders a view with the most recent updates to certain resources:

```<code>class AdminController < ApplicationController

    before_action :authenticate_user!
    layout "admin"

    def index
        @events = Event.last(3)
        @foos   = Foo.last(3)
        @bars   = Bar.last(3)
    end

end
</code>```

Now, I want to create a new event. So I have an Events controller:

```<code>class EventsController < ApplicationController

  before_action :authenticate_user!, only: [:new,:create]
  layout "admin", only: [:new]

  def index
    @events = Event.all
  end

  def show
  end

  def new
  end

  def create
  end

end
</code>```

But I want to display a list of events that have previously been added in the same view as the form for creating a new event. Should I retrieve all
the events in the new action? i.e.

```<code>def new
  @events = Event.all
end
</code>```

Or is there a better approach(perhaps more restful)?

答:
In my opinion, you should retrieve the events inside the 'new' action.

The more RESTful alternative would be to have separate methods (one for creating a new event and one for getting a list of previously added events) and then to call out to them  from the client in order to ultimately render the page/accept user input.

But, I do not like this approach because it increases the total load time on the client.  If you aren't building REST services, but web pages, it's usually better to just forget adhering the back-end strictly to REST; but things like having RESTful URLs are a good thing because they affect user experience.

If you really still need REST, you may consider having separate versions that call the same methods.  One action method to maximize page load time, and however many REST methods you need to separate your REST resources.


答:
Generally, type checking in Python is going to be ugly and require lots of extra code because Python isn't meant to be type checked. The general mantra with Python is (I have found): trust but verify.

What this means is that you should code mostly without type checking and let the user put in whatever values they want. If I want to make a circle that holds the value "hello world" as its radius, why not?

I should expect, however, that whenever I try to, let's say, scale this circle up the circle should throw an error. Probably a typerror because somewhere your code tried to use my str as an int or float. However, this is on the user.

You might ask why anyone would ever do this. Here's a nice example.

In a statictly typed language, like Haskell, we'd do something like this:

```<code>data Point = Point { x :: Int, y :: Int }
data Circle = Circle { c :: Point, r :: Int }
</code>```

Really, if we wanted full support we could replace the Int with a Num a => a but that requires RankNTypes and I don't want to get in to all that.

Now Point and Circle are datatypes that hold precisely the information we want and don't allow us to do anything silly. We can still make r negative, but we can't really defend against that easily.

If you want to fake something similar in Python you can do:

```<code>NUMBER = (float, int, long)

def check_type(value, types, error):
   if isinstance(value, types):
       return True
   raise TypeError(error)

class Point(object):
    __slots__ = ['x', 'y']
    def __init__(self, x, y):
        if check_type(x, NUMBER, "x should be a number."):
            self.x = x
        if check_type(y, NUMBER, "y should be a number"):
            self.y = y

 class Circle(object):
     __slots__ = ['c', 'r']
     def __init__(self, c, r):
         if check_type(c, Point, "c must be a Point"):
             self.c = c
         if check_type(x, NUMBER, "r must be a number"):
             self.r = r
</code>```

This is the cleanest way I can think to do it, and it's not very clean at all. Basically, what you're doing is abstracting away the type checking code into a function and supplying it with all the information. If you're looking for safety, this probably isn't the way to go anyway, because now the burden is just on the developer to provide all the right types.

For instance, in your original code you only checked for instances of int and float. However:

```<code>>>> x = 100000000000000000000000000000000000000000000
>>> isinstance(x, (float, int))
False
>>> type(x)
<type 'long'>
</code>```

Since you failed to accommodate this small idiosyncrasy, your end user could end up with unfixable bugs in their code because you provided the wrong types for checking. In a more type-oriented language, like Haskell from earlier, you can solve this with declarations like Num a => a. However, you can't do that in Python because Python was never meant for this kind of work.

There's even a bug in my code! What if the user wanted to have a circle in the complex plane instead of the real plane? I failed to add complex to my NUMBER tuple, so that would fail type checking.

Consider the alternative (mentioned in @Paddy3118's answer):

```<code>Point = namedtuple('Point', 'x', 'y')
Circle = namedtuple('Circle', 'c', 'r')
</code>```

Or, if you'd rather not have a separate Point type:

```<code>Circle = namedtuple('Circle', 'x', 'y', 'r')
</code>```

This code is short, concise, and provides exactly the functionality you need. If you need to add more methods you can do:

```<code>import math

class Circle(namedtuple('Circle', 'x', 'y', 'r'):
   __slots__ = ()
   def scale(scale_factor):
       self._replace(r = r * scale_factor)

   @property
   def area(self):
       return (math.pi ** 2) * (self.r)

   @property
   def circumference(self):
       return math.pi * 2 * self.r
</code>```

That last option is probably your best bet. It gives you the flexibility of Python's dynamic typing while still being a little bit conservative in what you can put in it.

Body:
Generally, type checking in Python is going to be ugly and require lots of extra code because Python isn't meant to be type checked. The general mantra with Python is (I have found): trust but verify.

What this means is that you should code mostly without type checking and let the user put in whatever values they want. If I want to make a circle that holds the value "hello world" as its radius, why not?

I should expect, however, that whenever I try to, let's say, scale this circle up the circle should throw an error. Probably a typerror because somewhere your code tried to use my str as an int or float. However, this is on the user.

You might ask why anyone would ever do this. Here's a nice example.

In a statictly typed language, like Haskell, we'd do something like this:

data Point = Point { x :: Int, y :: Int }
data Circle = Circle { c :: Point, r :: Int }

Really, if we wanted full support we could replace the Int with a Num a => a but that requires RankNTypes and I don't want to get in to all that.

Now Point and Circle are datatypes that hold precisely the information we want and don't allow us to do anything silly. We can still make r negative, but we can't really defend against that easily.

If you want to fake something similar in Python you can do:

NUMBER = (float, int, long)

def check_type(value, types, error):
   if isinstance(value, types):
       return True
   raise TypeError(error)

class Point(object):
    __slots__ = ['x', 'y']
    def __init__(self, x, y):
        if check_type(x, NUMBER, "x should be a number."):
            self.x = x
        if check_type(y, NUMBER, "y should be a number"):
            self.y = y

 class Circle(object):
     __slots__ = ['c', 'r']
     def __init__(self, c, r):
         if check_type(c, Point, "c must be a Point"):
             self.c = c
         if check_type(x, NUMBER, "r must be a number"):
             self.r = r

This is the cleanest way I can think to do it, and it's not very clean at all. Basically, what you're doing is abstracting away the type checking code into a function and supplying it with all the information. If you're looking for safety, this probably isn't the way to go anyway, because now the burden is just on the developer to provide all the right types.

For instance, in your original code you only checked for instances of int and float. However:

>>> x = 100000000000000000000000000000000000000000000
>>> isinstance(x, (float, int))
False
>>> type(x)
<type 'long'>

Since you failed to accommodate this small idiosyncrasy, your end user could end up with unfixable bugs in their code because you provided the wrong types for checking. In a more type-oriented language, like Haskell from earlier, you can solve this with declarations like Num a => a. However, you can't do that in Python because Python was never meant for this kind of work.

There's even a bug in my code! What if the user wanted to have a circle in the complex plane instead of the real plane? I failed to add complex to my NUMBER tuple, so that would fail type checking.

Consider the alternative (mentioned in @Paddy3118's answer):

Point = namedtuple('Point', 'x', 'y')
Circle = namedtuple('Circle', 'c', 'r')

Or, if you'd rather not have a separate Point type:

Circle = namedtuple('Circle', 'x', 'y', 'r')

This code is short, concise, and provides exactly the functionality you need. If you need to add more methods you can do:

import math

class Circle(namedtuple('Circle', 'x', 'y', 'r'):
   __slots__ = ()
   def scale(scale_factor):
       self._replace(r = r * scale_factor)

   @property
   def area(self):
       return (math.pi ** 2) * (self.r)

   @property
   def circumference(self):
       return math.pi * 2 * self.r

That last option is probably your best bet. It gives you the flexibility of Python's dynamic typing while still being a little bit conservative in what you can put in it.


答:
It looks like you're trying to reinvent python's property decorator.  There's a good question on StackOverflow about what use they are, and the top answer has exactly what you're trying to do here:  Real world example about how to use property feature in python?

Lets go back to the beginning, and use properties on your Circle instead:

A Circle - object should have three properties: two origin coordinates (some x, y) and a radius, in that (in our human visible world) x and y should be real numerical, a radius should be real positive numerical.

Initially, a basic Circle with no restrictions might look something like this:

```<code>class Circle(object):
   def __init__(self, x=0, y=0, radius=1):
      self.x = x
      self.y = y
      self.radius = radius
</code>```

Now checking that something "is numeric" goes against python's philosophy of duck typing, and as shown in the other answers, you'll probably get it wrong.  And besides, the instant you try to use them in a math equation, python is going to raise a TypeError anyway.

So this is how you might use property to keep radius from being negative, without having to futz around with attribute names inside __setattr__:

```<code>class Circle(object):
   def __init__(self, x=0, y=0, radius=1):
      self.x = x
      self.y = y
      self.radius = radius

   @property
   def radius(self):
      return self._radius

   @radius.setter
   def radius(self, radius):
      if radius < 0:
         raise ValueError('Radius cannot be negative')

      self._radius = radius
</code>```

Body:
It looks like you're trying to reinvent python's property decorator.  There's a good question on StackOverflow about what use they are, and the top answer has exactly what you're trying to do here:  Real world example about how to use property feature in python?

Lets go back to the beginning, and use properties on your Circle instead:

A Circle - object should have three properties: two origin coordinates (some x, y) and a radius, in that (in our human visible world) x and y should be real numerical, a radius should be real positive numerical.

Initially, a basic Circle with no restrictions might look something like this:

class Circle(object):
   def __init__(self, x=0, y=0, radius=1):
      self.x = x
      self.y = y
      self.radius = radius

Now checking that something "is numeric" goes against python's philosophy of duck typing, and as shown in the other answers, you'll probably get it wrong.  And besides, the instant you try to use them in a math equation, python is going to raise a TypeError anyway.

So this is how you might use property to keep radius from being negative, without having to futz around with attribute names inside __setattr__:

class Circle(object):
   def __init__(self, x=0, y=0, radius=1):
      self.x = x
      self.y = y
      self.radius = radius

   @property
   def radius(self):
      return self._radius

   @radius.setter
   def radius(self, radius):
      if radius < 0:
         raise ValueError('Radius cannot be negative')

      self._radius = radius


问:
Do you really have to do BDD/TDD in a test first manner?
Even though I haven't been in a TDD or BDD project, or I have been in some that say they are doing TDD but are pretty far from it, these are things that I think about and really try to read as much as I can about.

Back to the question. When you're doing BDD you should write your "test" first and make it fail, right? And then implement that feature or what you call it. But if you take this to the extreme couldn't this be some kind of top-down development? You're looking at your UI and says, "I would like to have this feature/behavior here". Then you fix your UI to implement that feature and the code that supports the UI. At this point you haven't implemented any business logic or data access logic, you have just implemented your behavior. What I'm aiming at instead of writing the test first you write your UI code first. In some cases it should result in the same code for the data access and business layer, since you use your UI code to define what your business needs to support.

Of course you should complement this with tests that is used to make sure that the feature is working as it should in the feature.

Any thoughts?

答: If you don't write your tests first you are not driving development through your tests. Ergo, you're not doing test-driven development!</p>


问:
what kind of functions and/or classes are impossible to unit test and why
Main excuse from the developer for not having a good unit testing is "Code is not designed in a unit testable fashion." I am trying to understand what type of design and code that can't be unit tested. </p>

答:
The are a few areas that can make it more difficult to write unit tests for.  However, I would stress that that doesn't mean you should discount useful techniques out of hand simply because they may add some complexity to your testing.  As with any coding you should be doing your own analysis to determine if the benefits outway the costs, and not blindly accept what some random guy posts on the net.

Poorly written of designed code

inappropriate coupling (usually tight coupling where it shouldn't be)

kitchen sink code (where a function has far too much logic/responsibilities)

Reliance of state in a different scope

The cost for most of these spiral out of control unless you know what your doing.  Unfortunately, many often don't know how to use these techniques in ways to mitigate things like testing complexity.

Singletons

Globals

Closures

External/System State

Hardware/device dependencies

Network dependencies

Filesystem dependencies

Inter-process dependencies

Other system call dependencies

Concurrency

Threading (locks, critical sections, etc)

fork'ing

Coroutines

Call Backs

Signal Handlers (not all, but some)