问:
Which Continuous Integration for Selenium 2 with TestNG
So I have a Selenium Automation project (using Maven).
I'd like to be able to set my tests to run overnight and possibly email a report daily to the team.
Which CI would be most suitable for TestNG.xml suites?

I tried Hudson but I couldn't figure out a way to execute TestNG files from the build?

Thanks in advance.

答: You should be able to use Hudson to kick off a Maven job (Hudson has a Maven plugin http://wiki.hudson-ci.org/display/HUDSON/Maven+2+Project+Plugin works with maven 3) that runs your test, see http://testng.org/doc/maven.html


答:
There are different ways that you may try and Hudson is one of them. However, you might not find a good resource or article to follow.

Here is a nice walk-through how to succeed - Continuous Integration with Selenium

I would also recommend to look at TestNG and Advanced Concepts book for a complete reference.

ContentLicense: CC BY-SA 3.0

Title: Which Continuous Integration for Selenium 2 with TestNG

Body:
So I have a Selenium Automation project (using Maven).
I'd like to be able to set my tests to run overnight and possibly email a report daily to the team.
Which CI would be most suitable for TestNG.xml suites?

I tried Hudson but I couldn't figure out a way to execute TestNG files from the build?

Thanks in advance.


问:
conventions for friend methods in Perl
Perl doesn't support a friend relationship between objects, nor does it support private or protected methods. What is usually done for private methods is to prefix the name with an underscore. I occasionally have methods that I think of as friend methods. Meaning that I expect them to be used by a specific object, or an object with a specific responsibility, but I'm not sure if I should make that method public (meaning foo ) or private ( _foo ) or if there's a better convention? is there a convention for friend methods?

答: I'm not aware of any conventions or best practices for friend methods that the Perl community uses.  If you felt the need to designate a prefix for these methods I don't see any real issue with it, but I don't see any advantage in it either.  Personally I'd just make it a "public" method, without the underscore, and without any additional prefix.</p>

Title: conventions for friend methods in Perl


问:
Programming languages with a Lisp-like syntax extension mechanism
I have only a limited knowledge of Lisp (trying to learn a bit in my free time) but as far as I understand Lisp macros allow to introduce new language constructs and syntax by describing them in Lisp itself. This means that a new construct can be added as a library, without changing the Lisp compiler / interpreter.

This approach is very different from that of other programming languages. E.g., if I wanted to extend Pascal with a new kind of loop or some particular idiom I would have to extend the syntax and semantics of the language and then implement that new feature in the compiler.

Are there other programming languages outside the Lisp family (i.e. apart from Common Lisp, Scheme, Clojure (?), Racket (?), etc) that offer a similar possibility to extend the language within the language itself?

EDIT

Please, avoid extended discussion and be specific in your answers. Instead of a long list of programming languages that can be extended in some way or another, I would like to understand from a conceptual point of view what is specific to Lisp macros as an extension mechanism, and which non-Lisp programming languages offer some concept that is close to them.

答:
Converge is another one non-lispy metaprogramming language. And, to some extent, C++ qualifies too.

Arguably, MetaOCaml is quite far from Lisp. For a totally different style of syntax extensibility, but yet quite powerful, take a look at CamlP4.

Nemerle is another extensible language with a Lisp-style metaprogramming, although it is closer to languages like Scala.

And, Scala itself will soon become such a language too.

Edit: I forgot about the most interesting example - JetBrains MPS. It is not only very distant from anything Lispish, it is even a non-textual programming system, with an editor operating directly on an AST level.

Edit2: To answer an updated question - there is nothing unique and exceptional in the Lisp macros. In theory, any language can provide such a mechanism (I even did it with plain C). All you need is an access to your AST and an ability to execute code in compilation time. Some reflection might help (querying about the types, the existing definitions, etc.).


答:
Perl does not, by itself, enforce private methods or attributes, no. In fact, Larry Wall was once quoted as saying:

Perl doesn't have an infatuation with enforced privacy. It would
  prefer that you stayed out of its living room because you weren't
  invited, not because it has a shotgun.

If you're using Moose (and if you aren't, you really, really should), you could put your method, which I'll call foo, into a role, say Fooable, that can be composed into more than one class, thus allowing foo to be a method in any class that does the Fooable role.

If you want true privacy, though, it looks as though MooseX::Privacy provides that, although I don't have any experience using it.

Title: conventions for friend methods in Perl

Body: Perl doesn't support a friend relationship between objects, nor does it support private or protected methods. What is usually done for private methods is to prefix the name with an underscore. I occasionally have methods that I think of as friend methods. Meaning that I expect them to be used by a specific object, or an object with a specific responsibility, but I'm not sure if I should make that method public (meaning foo ) or private ( _foo ) or if there's a better convention? is there a convention for friend methods?


问:
What is an efficient algorithm for randomly assigning a pool of objects to a parent using specific rules
I need some expert answers to help me determine the most efficient algorithm in this scenario.

Consider the following data structures:

```<code>type B { A parent; }

type A {
   set<B> children;
   integer minimumChildrenAllowed;
   integer maximumChildrenAllowed;
}
</code>```

I have a situation where I need to fetch all the orphan children (there could be hundreds of thousands of these) and assign them RANDOMLY to A type parents based on the following rules.

At the end of the job, there should be no orphans left

At the end of the job, no object A should have less children than its predesignated minimum.

At the end of the job, no object A should have more children than its predesignated maximum.

If we run out of A objects then we should create a new A with default values for minimum and maximum and assign remaining orphans to these objects.

The distribution of children should be as evenly distributed as possible.

There may already be some children assigned to A before the job starts.

I was toying with how to do this but I am afraid that I would just end up looping across the parents sorted from smallest to largest, and then grab an orphan for each parent.

I was wondering if there is a more efficient way to handle this?

EDIT:

Expanding upon the criteria for even distribution of children, we should attempt to avoid a situation where any one A has 2 or more children than any other A unless they started that way.  For example, if A1 has 4 children, and A2 and A3 have 1 child each and there are 2 orphans, then A2 and A3 should each be assigned an orphan making an even distribution of 4, 3, and 3 children for each A.

Yes I understand we could end up where there is one orphan left and an A that has not met its minimum.  This exception case will be handled by a separate algorithm that will try to evenly split an A into two objects and assign the remaining orphans amongst them.

EDIT: 2

Ok, I misunderstood the requirements in my situation.  The data model for A shows minimum and maximum property but in fact this should be a global setting for every A.  In essence it is a missed requirement that requires the data model to be refactored later.

All A will have the same minimum and maximum now.  This actually changes things significantly!  Sorry for the confusion.

答:
I would:

Calculate max*countOfA and min*CountOfA

If you don't have enough B to fill all the minimum A values you can't actually meet the criteria you have listed.

If you don't have enough A then add the minimum number you need (ceiling of (SumOfAMaxes-B)/DefaultMaximum).  Update the sum of min and max values accordingly.

You can now calculate the mean number of children for your set A.  This is your target value.  However, this will usually be fractional.  Figure out how many items should be rounded down, and how many up.  (Example, you have 100 parents and the mean is 3.4.  40 will have 3 as the target, and 60 will have 4 as the target).

Loop through the parents and set them to the higher target value unless they are already that value or higher.  Keep track of how many children you have left to allocate as you go.  When you run out of the high value (in the above example you would have only 60 of them), assign the lower value.

When you are done with 4 you may have some unassigned children because of existing parents that had more children than your target value.  If so go back to step 4 but make sure your new target value is at least equal to the floor of the prior target value + 1.

This probably isn't optimal but it's pretty easy and probably not that far off optimal.  It is quite similar to the original comment by mcwise, though a little improved and elaborated.  Given the updated requirements there isn't that much to the problem.


答:
There are tools that allow making custom languages without writing a whole compiler from scratch. For example there is Spoofax, which is a code transformation tool: you put in input grammar and transformation rules (written in a very high level declarative way), and then you can generate Java source code (or other language, if you care enough) from a custom language designed by you.

So, it would be possible to take grammar of language X, define grammar of language X' (X with your custom extensions) and transformation X'→X, and Spoofax will generate a compiler X'→X.

Currently, if I understand correctly, the best support is for Java, with C# support being developed (or so I heard). This technique could be applied to any language with static grammar (so, e.g. probably not Perl) though.

Title: Programming languages with a Lisp-like syntax extension mechanism

Body:
I have only a limited knowledge of Lisp (trying to learn a bit in my free time) but as far as I understand Lisp macros allow to introduce new language constructs and syntax by describing them in Lisp itself. This means that a new construct can be added as a library, without changing the Lisp compiler / interpreter.

This approach is very different from that of other programming languages. E.g., if I wanted to extend Pascal with a new kind of loop or some particular idiom I would have to extend the syntax and semantics of the language and then implement that new feature in the compiler.

Are there other programming languages outside the Lisp family (i.e. apart from Common Lisp, Scheme, Clojure (?), Racket (?), etc) that offer a similar possibility to extend the language within the language itself?

EDIT

Please, avoid extended discussion and be specific in your answers. Instead of a long list of programming languages that can be extended in some way or another, I would like to understand from a conceptual point of view what is specific to Lisp macros as an extension mechanism, and which non-Lisp programming languages offer some concept that is close to them.


问:
Does software testing methodology rely on flawed data?
It’s a well-known fact in software engineering that the cost of fixing a bug increases exponentially the later in development that bug is discovered. This is supported by data published in Code Complete and adapted in numerous other publications.

However, it turns out that this data never existed. The data cited by Code Complete apparently does not show such a cost / development time correlation, and similar published tables only showed the correlation in some special cases and a flat curve in others (i.e. no increase in cost).

Is there any independent data to corroborate or refute this?

And if true (i.e. if there simply is no data to support this exponentially higher cost for late discovered bugs), how does this impact software development methodology?

答:
Another Answer! This time to address the title question "Does software morhtodoligy rely on flawed data".

The real answer is "there is no data". As in there is no large reliable body of data on software projects there defects, successes time to market etc.

All attempts to gather such data have been underfunded, statistically flawed, or,, so specific to a particular project it is not possible to derive general conclusions from.

Furthermore I do not think there ever will be, the software development process is too subjective and slippery for strict measurement. The organizations best placed to gather such data (the large software houses and systems integrators) know in their hearts that any figures gathered from their performance would be deeply embarrassing.

The only organizations that publish numbers on the cost and success of software projects

are government departments, and, only then because they have to, and, yes these numbers are deeply embarrassing no matter how much they massage the figures.

So in conclusion all software studies are necessarily purely  subjective because there is no real data on which to base an objective conclusion.


问:
What's special in July 26th and why is it used in examples for Expires header so often?
I've noticed that July 26th (my birthday) is used really often in various PHP examples related to preventing http caching using Expires header, like:

https://stackoverflow.com/questions/12398714/cache-issue-with-private-networking-stream

https://stackoverflow.com/questions/2833305/how-to-expire-page-in-php-when-user-logout

http://expressionengine.com/archived_forums/viewthread/81945/

What's special in that date?

答: Only thing I could find was the release of Mac OS 8. Not related to CSS release dates, HTML, XML, PHP, Javascript, Internet Explorer, Nescape Navigator, Apache Foundation, MySQL, or anything else relevant I could wrack my brain for. I suspect it's probably someone's kid's birthday or anniversary or something. In short, it's a coincidence. </p>


答: Probably somebody did that as an example of a cache expires a long time ago and then everybody copied it.  Interestingly it's often expressed as "Mon, 26 July 1997", but the actual date occurred on a Saturday.  It's not that interesting in terms of UTC seconds (seconds since 1970) since it is 869893200. Maybe it's just an example of CTRL-C/CTRL-V coding?</p>

Title: What's special in July 26th and why is it used in examples for Expires header so often?

Body:
I've noticed that July 26th (my birthday) is used really often in various PHP examples related to preventing http caching using Expires header, like:

https://stackoverflow.com/questions/12398714/cache-issue-with-private-networking-stream

https://stackoverflow.com/questions/2833305/how-to-expire-page-in-php-when-user-logout

http://expressionengine.com/archived_forums/viewthread/81945/

What's special in that date?


问:
"Do you have any questions for us?" In an interview
You know the prospective company fairly well but are asked "Do you have any questions for us?".  To show interest, what are some of your favorite questions to reply?</p>

答:
To find some good answers here, you might ask yourself why do they ask that question?

Usualy a Human Resource person is asking that question to see wether you are prepared for the interview or not. So in this scenario you should ask something about

the company in general

empoyment conditions

education plans etc

For technical persons there are two options: maybe they ask just because they run out of questions by there own or they really want to found out something about our expertice. As a regular interviewer myself I can tell you that it's not the answers that tell you someting about the know-how of a person but the questions do...

So for technical questions you should try to ask something that is related to the job you are after.

ContentLicense: CC BY-SA 2.5


问:
Caching factory design
I have a factory class XFactory that creates objects of class X. Instances of X are very large, so the main purpose of the factory is to cache them, as transparently to the client code as possible. Objects of class X are immutable, so the following code seems reasonable:

```<code># module xfactory.py
import x
class XFactory:
  _registry = {}

  def get_x(self, arg1, arg2, use_cache = True):
    if use_cache:
      hash_id = hash((arg1, arg2))
      if hash_id in _registry:
        return _registry[hash_id]
    obj = x.X(arg1, arg2)
    _registry[hash_id] = obj
    return obj

# module x.py
class X:
  # ...
</code>```

Is it a good pattern? (I know it's not the actual Factory Pattern.) Is there anything I should change?

Now, I find that sometimes I want to cache X objects to disk. I'll use pickle for that purpose, and store as values in the _registry the filenames of the pickled objects instead of references to the objects. Of course, _registry itself would have to be stored persistently (perhaps in a pickle file of its own, in a text file, in a database, or simply by giving pickle files the filenames that contain hash_id).

Except now the validity of the cached object depends not only on the parameters passed to get_x(), but also on the version of the code that created these objects.

Strictly speaking, even a memory-cached object could become invalid if someone modifies x.py or any of its dependencies, and reloads it while the program is running. So far I ignored this danger since it seems unlikely for my application. But I certainly cannot ignore it when my objects are cached to persistent storage.

What can I do? I suppose I could make the hash_id more robust by calculating hash of a tuple that contains arguments arg1 and arg2, as well as the filename and last modified date for x.py and every module and data file that it (recursively) depends on. To help delete cache files that won't ever be useful again,  I'd add to the _registry the unhashed representation of the modified dates for each record.

But even this solution isn't 100% safe since theoretically someone might load a module dynamically, and I wouldn't know about it from statically analyzing the source code. If I go all out and assume every file in the project is a dependency, the mechanism will still break if some module grabs data from an external website, etc.).

In addition, the frequency of changes in x.py and its dependencies is quite high, leading to heavy cache invalidation.

Thus, I figured I might as well give up some safety, and only invalidate the cache only when there is an obvious mismatch. This means that class X would have a class-level cache validation identifier that should be changed whenever the developer believes a change happened that should invalidate the cache. (With multiple developers, a separate invalidation identifier is required for each.) This identifier is hashed along with arg1 and arg2 and becomes part of the hash keys stored in _registry.

Since developers may forget to update the validation identifier or not realize that they invalidated existing cache, it would seem better to add another validation mechanism: class X can have a method that returns all the known "traits" of X. For instance, if X is a table, I might add the names of all the columns. The hash calculation will include the traits as well.

I can write this code, but I am afraid that I'm missing something important; and I'm also wondering if perhaps there's a framework or package that can do all of this stuff already. Ideally, I'd like to combine in-memory and disk-based caching.

EDIT:

It may seem that my needs can be served well by a pool pattern. On further investigation, however, it’s not the case. I thought I'd list the differences:

Can an object be used by multiple clients?

Pool: No, each object needs to be checked out and then checked in when no longer needed. The precise mechanism may be complicated.

XFactory: Yes. Objects are immutable, and can be used by infinitely many clients at once. There’s never a need to create a second copy of the same object.

Does pool size need to be controlled?

Pool: Often, yes. If so, the strategy to do so may be quite complicated.

XFactory: No. An object must be delivered on demand to the client, and if an existing object is unsuitable, a new one needs to be created.

Are all objects freely substitutable?

Pool: Yes, the objects are typically freely substitutable (or if not, it’s trivial to check which object the client needs).

XFactory: Absolutely not, and it’s very hard to find out if a given object can service a given client request. It depends on whether an existing object is available that was created with (a) the same arguments and (b) the same version of the source code. Part (b) cannot be verified by XFactory, so it asks the client to help. The client fulfills this responsibility in two ways. First, the client may increment any of its several designated internal version counters (one per developer). This cannot happen in runtime, only a developer may change these counters when he believes that the source code change makes existing objects unusable. Second, a client will return some invariants about the objects that it needs, and XFactory will verify that these invariants are not violated before serving the object to the client. If any of these checks fail, XFactory will create and deliver a new object.

Does performance impact need careful analysis?

Pool: Yes, in some cases a pool actually hurts performance if the overhead of object management is greater than the overhead of object creation/destruction.

XFactory: No. The computation costs of the objects in question is known to be very high, and loading them from memory or from disk is without doubt superior than recalculating them from scratch.

When are objects destroyed?

Pool: When the pool is shut down. Perhaps it might also destroy objects if told to (partially) release resources or if certain objects have not been used for a while.

XFactory: Whenever an object was created with the version of the source code that is no longer current, as evidenced by either invariant violation or counter mismatch. The process of locating and destroying such objects at the right time is quite complicated. In addition, time-based invalidation of all objects may be implemented to reduce the accumulated risks of using invalid objects. Since XFactory is never certain that it is the sole owner of an object, such invalidation is best achieved by an additional “version counter” in the client objects, which is incremented programmatically on a periodic basis, rather than by a developer.

What special considerations exist for multithreaded environment?

Pool: Has to avoid collisions in object checking out / checking in (don’t want to check out an object to two clients)

XFactory: Has to avoid collision in object creation (don’t want to create two objects based on two identical requests)

What needs to be done if client does not release an object?

Pool: It may want to make the object available to others after waiting for some time.

XFactory: Not applicable. Clients do not notify XFactory about when they are done with the object.

Do objects need to be modified?

Pool: May have to be reset to the default state before being reused.

XFactory: No, the objects are immutable.

Are there any special considerations related to persistence of objects?

Pool: Typically not. A pool is about saving the cost of object creation, so all the objects are kept in memory (reading from disk would defeat the purpose).

XFactory: Yes, XFactory is about saving the cost of performing complex calculations, so storing pre-calculated objects on disk makes sense.  As a result XFactory needs to deal with the typical problems of persistent storage; e.g. at initialization, it needs to connect to persistent storage, obtain from it the metadata about which objects are currently available there, and be ready to load them into memory if requested. And object may be in one of three states: “doesn’t exist”, “exists on disk”, “exists in memory”. While XFactory is running, the state may change only in one direction (to the right in this sequence).

In summary, the pool's complexity is in items 1, 2, 4, 6, and possibly 5, 7, 8. The XFactory complexity is in items 3, 6, 9. The only overlap is item 6, and it’s really not the core function of either pool or XFactory, but rather a constraint on the design that is common to any pattern that needs to work in a multithreaded environment.

答:
Your concerns are very much valid and they tell me your original easy caching solution is eventually becoming part of your architecture which naturally brings a new level of issues as you described yourself.

A good architectural solution to caching is to use annotations combined with IoC which solves several problems you described. For example:

Allow you to better control the life-cycle of your cached objects

Allow you to replace the caching behavior easily by changing the annotations (instead of changing the implementation)

Let you easily configure a multi-layered cache where you could be storing in memory then disk cache for example

Let you define the key (hash) for each method in the annotation itself

In my projects (Java or C#) I use Spring caching annotations. You can find a brief description here.

IoC is a key concept in this solution because it allows you to configure your caching system anyway you want.

In order to implement a similar solution in Python you have to find how to use annotations and search for a IoC container that allows you to build proxies. That's how the annotations work in order to intercept all method calls and provide you this particular solution for caching.

Title: Caching factory design


答:
Assuming you have existing A's with various numbers of B's already assigned to them, my first pass at this would probably be:

Sort the A's first on their number of B's (will call that the ChildCount), and then on a random number as the second sort factor.  So you have a list of A's grouped by their ChildCount, lowest first, but then those with the same child count are randomly placed on the list amongst themselves.  Then just start from the top, assigning B's one at a time to those A's with a ChildCount of 0.  When thats done, start back at the top and do it for those with a ChildCount of 1.  Then 2, etc.  If an A reaches its max number of children, remove it from the list altogether.  If you have a few B's left over, create the new A's and fill them up one at a time.  To avoid 'orphans', if you mark the newly assigned B's as being new, you can take a few of those back from other A's with a max count, and balance things out (assuming this would be ok to do during 'assign time', and before everything is committed).

Title: What is an efficient algorithm for randomly assigning a pool of objects to a parent using specific rules

Body:
I need some expert answers to help me determine the most efficient algorithm in this scenario.

Consider the following data structures:

```<code>type B { A parent; }

type A {
   set<B> children;
   integer minimumChildrenAllowed;
   integer maximumChildrenAllowed;
}
</code>```

I have a situation where I need to fetch all the orphan children (there could be hundreds of thousands of these) and assign them RANDOMLY to A type parents based on the following rules.

At the end of the job, there should be no orphans left

At the end of the job, no object A should have less children than its predesignated minimum.

At the end of the job, no object A should have more children than its predesignated maximum.

If we run out of A objects then we should create a new A with default values for minimum and maximum and assign remaining orphans to these objects.

The distribution of children should be as evenly distributed as possible.

There may already be some children assigned to A before the job starts.

I was toying with how to do this but I am afraid that I would just end up looping across the parents sorted from smallest to largest, and then grab an orphan for each parent.

I was wondering if there is a more efficient way to handle this?

EDIT:

Expanding upon the criteria for even distribution of children, we should attempt to avoid a situation where any one A has 2 or more children than any other A unless they started that way.  For example, if A1 has 4 children, and A2 and A3 have 1 child each and there are 2 orphans, then A2 and A3 should each be assigned an orphan making an even distribution of 4, 3, and 3 children for each A.

Yes I understand we could end up where there is one orphan left and an A that has not met its minimum.  This exception case will be handled by a separate algorithm that will try to evenly split an A into two objects and assign the remaining orphans amongst them.

EDIT: 2

Ok, I misunderstood the requirements in my situation.  The data model for A shows minimum and maximum property but in fact this should be a global setting for every A.  In essence it is a missed requirement that requires the data model to be refactored later.

All A will have the same minimum and maximum now.  This actually changes things significantly!  Sorry for the confusion.


答:
This is partly a question of semantics. The basic idea of Lisp is that the program is data that can itself be manipulated. Commonly-used languages in the Lisp family, like Scheme, don't really let you add new syntax in the parser sense; it's all just space-delimited parenthesized lists. It's just that since the core syntax does so little, you can make almost any semantic construct out of it. Scala (discussed below) is similar: the variable-name rules are so liberal that you can easily make nice DSLs out of it (while staying within the same core syntax rules).

These languages, while they don't actually let you define new syntax in the sense of Perl filters, have a sufficiently flexible core that you can use it to build DSLs and add language constructs.

The important common feature is that they let you define language constructs that work as well as built-in ones, using features exposed by the languages. The degree of support for this feature varies:

Many older languages provided built-in functions like sin(), round(), etc., without any way to implement your own.

C++ provides limited support. For example some built-in keywords like casts (static_cast<target_type>(input), dynamic_cast<>(), const_cast<>(), reinterpret_cast<>()) can be emulated using template functions, which Boost uses for lexical_cast<>(), polymorphic_cast<>(), any_cast<>(), ....

Java has built-in control structures (for(;;){}, while(){}, if(){}else{}, do{}while(), synchronized(){}, strictfp{}) and doesn't let you define your own. Scala instead defines an abstract syntax that lets you call functions using a convenient control-structure-like syntax, and libraries use this to effectively define new control structures (e.g. react{} in the actors library).

Also, you might look at Mathematica's custom syntax functionality in the Notation package. (Technically it is in the Lisp family, but has some extensibility features done differently, as well as the usual Lisp extensibility.)


答:
Metalua is a language and a compiler compatible with Lua that provides this.

Full compatibility with Lua 5.1 sources and bytecode: clean, elegant    semantics and syntax, amazing expressive power, good
  performances,    near-universal portability.
  -  A complete macro system, similar in power to what's offfered by Lisp dialects or Template Haskell; manipulated programs can be seen

  as source code, as abstract syntax trees, or as an arbitrary mix

  thereof, whichever suits your task better.

A dynamically extensible parser, which lets you support your macros with a syntax that blends nicely with the rest of the    language.

A set of language extensions, all implemented as regular metalua macros.

Differences with Lisp:

Don't bother developers with macros when they aren't writing one: the language's syntax and semantics should be best suited for those
  95% of the time when we aren't writing macros.

Encourage developers to follow the conventions of the language: not only with "best practices rants" nobody listen to, but by offering
  an API that makes it easier to write things the Metalua Way.
  Readability by fellow developers is more important and more difficult
  to achieve than readability by compilers, and for this, having a
  common set of respected conventions helps a lot.

Yet provide all the power one's willing to handle. Neither Lua nor Metalua are into mandatory bondage and discipline, so if you know what
  you're doing, the language won't get in your way.

Make it obvious when something interesting happens: all meta-operations happen between +{...} and -{...}, and visually stick
  out of the regular code.

An exemple of application is the implementation of ML-like pattern matching.

See also : http://lua-users.org/wiki/MetaLua


问:
At what point is asynchronous reading of disk I/O more efficient than synchronous?
Assuming there is some bit of code that reads files for multiple consumers, and the files are of any arbitrary size: At what size does it become more efficient to read the file asynchronously? Or to put it another way, how small must a file be for it to be faster just to read it synchronously?

I've noticed (and perhaps I'm incorrect) that when reading very small files, it takes longer to read them asynchronously than synchronously (in particular with .NET). I'm assuming this has to do with set up time for things like I/O Completion Ports, threads, etc.

Is there any rule of thumb to help out here? Or is it dependent on the system and the environment?

答:
I think the problem here is not so much read speeds, as it's the latency.

If you're reading from a network drive, or from a slow mechanical hard disk drive with long queues, the performance will take a nosedive for reading. And if your app is also doing the reading in GUI thread, in which case it's a very bad application, then it will be awful for the user.


问:
Functional Languages that compile to Android's Dalvik VM?
I have a software problem that fits the functional approach to programming, but the target market will be on the Android OS.  I ask because there are functional languages that compile to Java's VM, but Dalvik bytecode != Java bytecode.

Alternatively, do you know if the dx utility can intelligently convert the .class files generated from functional languages like Scala?

Edit:
In order to add a bit more helpfulness to the community, and also to help me choose better, can I refine the question a bit?

Have you used any alternate languages with Dalvik?  Which ones?

What are some "gotchas" (problems) that I might run into?

Is performance acceptable?  By that, I mean the application still feels responsive to the user.

I've never done mobile phone development, but I grew up on constrained devices and I'm under no illusion that there is a cost to using non-standard languages with the platform.  I just need to know if the cost is such that I should shoe-horn my approach into default language (i.e. apply functional principles in the OOP language).

答:
Beside scala I may suggest you to have a look on mirah on android, here are some details: http://threebrothers.org/brendan/blog/strange-loop-2011-mirah-for-android-development/

So what makes this approach 'better' than the other languages? Mirah is a static typed language with resemblance to ruby. Which allows for some functional style arguably better than java.Usually 'porting' a language to android is problematic because you need to port the standard library too. Mirah avoids this by avoiding to have a standard lib. In the referenced material there is a nice overview from REAL WORLD experience running mirah on android and how it turned out.
(try 2)


问:
Why are many programmers moving their code to github?
For the past 6 months or more, I've been seeing many codes hosted at sourceforge.net as well as other hosting sites "Move to GitHub". A mere Google Search with the phrase "Moved to Github" returns several results containing the text moved to github. This is very confusing for me, and I'm wondering, why exactly are people moving? Does it mean that GitHub is better or is there some special advantage I'm not seeing?</p>

答:
Sourceforge also offers Git, but Github just does it better (for now).

Their pull request system works nicely (much better than Gitorious for instance)

Their recently-upgraded notification is very convenient.

They show the code right away

Their killer feature, in my opinion, is the "Network graph":

Difference with gitk: it also shows you what is going on in other people's branches (without having to pull their branches), which is very important when collaborating.


问:
How do software patches and updates work?
So, how exactly do software patches work. If there is a certain bug in the source code of a program, how is this source code changed when one installs a patch? After the patch has been installed how is the program 'automatically' rebuilt? </p>

答:
The whole program gets updated. In essence the operation could go as follows:

Request updates

Download updated files

Replace current files with the new downloaded files

Details how to manage this may vary, because for example it might not be possible to delete an executable file of a running process, so some form of a workaround is needed(run the updater as a separate program instead of the main application...). It could also be possible to simply just apply the actual changes between the old and the new file, rather than download the whole file. But again, these are just implementation details.


答:
The way I see it the cache is fine - X is not.

IMHO de-serialization of single instances should not be an issue of the cache. It is a task for the according class. The main issue here is that this class is changing frequently. I suggest to separate the concern of caching instances and the concern of de-serializing the object. The latter has to be improved so that X can de-serialize older formats as well. This might be very tricky and expensive. If it is too expensive, you must ask yourself do you really need to load old versions as long as X is changing frequently?

BTW a version identifier seems mandatory. Without further knowledge of the structure of X I can only make some guesses, but the structure of X seems to be logically modular (e.g. you spoke of traits). If so, maybe it would help to make this structure explicit.

Title: Caching factory design

Body:
I have a factory class XFactory that creates objects of class X. Instances of X are very large, so the main purpose of the factory is to cache them, as transparently to the client code as possible. Objects of class X are immutable, so the following code seems reasonable:

```<code># module xfactory.py
import x
class XFactory:
  _registry = {}

  def get_x(self, arg1, arg2, use_cache = True):
    if use_cache:
      hash_id = hash((arg1, arg2))
      if hash_id in _registry:
        return _registry[hash_id]
    obj = x.X(arg1, arg2)
    _registry[hash_id] = obj
    return obj

# module x.py
class X:
  # ...
</code>```

Is it a good pattern? (I know it's not the actual Factory Pattern.) Is there anything I should change?

Now, I find that sometimes I want to cache X objects to disk. I'll use pickle for that purpose, and store as values in the _registry the filenames of the pickled objects instead of references to the objects. Of course, _registry itself would have to be stored persistently (perhaps in a pickle file of its own, in a text file, in a database, or simply by giving pickle files the filenames that contain hash_id).

Except now the validity of the cached object depends not only on the parameters passed to get_x(), but also on the version of the code that created these objects.

Strictly speaking, even a memory-cached object could become invalid if someone modifies x.py or any of its dependencies, and reloads it while the program is running. So far I ignored this danger since it seems unlikely for my application. But I certainly cannot ignore it when my objects are cached to persistent storage.

What can I do? I suppose I could make the hash_id more robust by calculating hash of a tuple that contains arguments arg1 and arg2, as well as the filename and last modified date for x.py and every module and data file that it (recursively) depends on. To help delete cache files that won't ever be useful again,  I'd add to the _registry the unhashed representation of the modified dates for each record.

But even this solution isn't 100% safe since theoretically someone might load a module dynamically, and I wouldn't know about it from statically analyzing the source code. If I go all out and assume every file in the project is a dependency, the mechanism will still break if some module grabs data from an external website, etc.).

In addition, the frequency of changes in x.py and its dependencies is quite high, leading to heavy cache invalidation.

Thus, I figured I might as well give up some safety, and only invalidate the cache only when there is an obvious mismatch. This means that class X would have a class-level cache validation identifier that should be changed whenever the developer believes a change happened that should invalidate the cache. (With multiple developers, a separate invalidation identifier is required for each.) This identifier is hashed along with arg1 and arg2 and becomes part of the hash keys stored in _registry.

Since developers may forget to update the validation identifier or not realize that they invalidated existing cache, it would seem better to add another validation mechanism: class X can have a method that returns all the known "traits" of X. For instance, if X is a table, I might add the names of all the columns. The hash calculation will include the traits as well.

I can write this code, but I am afraid that I'm missing something important; and I'm also wondering if perhaps there's a framework or package that can do all of this stuff already. Ideally, I'd like to combine in-memory and disk-based caching.

EDIT:

It may seem that my needs can be served well by a pool pattern. On further investigation, however, it’s not the case. I thought I'd list the differences:

Can an object be used by multiple clients?

Pool: No, each object needs to be checked out and then checked in when no longer needed. The precise mechanism may be complicated.

XFactory: Yes. Objects are immutable, and can be used by infinitely many clients at once. There’s never a need to create a second copy of the same object.

Does pool size need to be controlled?

Pool: Often, yes. If so, the strategy to do so may be quite complicated.

XFactory: No. An object must be delivered on demand to the client, and if an existing object is unsuitable, a new one needs to be created.

Are all objects freely substitutable?

Pool: Yes, the objects are typically freely substitutable (or if not, it’s trivial to check which object the client needs).

XFactory: Absolutely not, and it’s very hard to find out if a given object can service a given client request. It depends on whether an existing object is available that was created with (a) the same arguments and (b) the same version of the source code. Part (b) cannot be verified by XFactory, so it asks the client to help. The client fulfills this responsibility in two ways. First, the client may increment any of its several designated internal version counters (one per developer). This cannot happen in runtime, only a developer may change these counters when he believes that the source code change makes existing objects unusable. Second, a client will return some invariants about the objects that it needs, and XFactory will verify that these invariants are not violated before serving the object to the client. If any of these checks fail, XFactory will create and deliver a new object.

Does performance impact need careful analysis?

Pool: Yes, in some cases a pool actually hurts performance if the overhead of object management is greater than the overhead of object creation/destruction.

XFactory: No. The computation costs of the objects in question is known to be very high, and loading them from memory or from disk is without doubt superior than recalculating them from scratch.

When are objects destroyed?

Pool: When the pool is shut down. Perhaps it might also destroy objects if told to (partially) release resources or if certain objects have not been used for a while.

XFactory: Whenever an object was created with the version of the source code that is no longer current, as evidenced by either invariant violation or counter mismatch. The process of locating and destroying such objects at the right time is quite complicated. In addition, time-based invalidation of all objects may be implemented to reduce the accumulated risks of using invalid objects. Since XFactory is never certain that it is the sole owner of an object, such invalidation is best achieved by an additional “version counter” in the client objects, which is incremented programmatically on a periodic basis, rather than by a developer.

What special considerations exist for multithreaded environment?

Pool: Has to avoid collisions in object checking out / checking in (don’t want to check out an object to two clients)

XFactory: Has to avoid collision in object creation (don’t want to create two objects based on two identical requests)

What needs to be done if client does not release an object?

Pool: It may want to make the object available to others after waiting for some time.

XFactory: Not applicable. Clients do not notify XFactory about when they are done with the object.

Do objects need to be modified?

Pool: May have to be reset to the default state before being reused.

XFactory: No, the objects are immutable.

Are there any special considerations related to persistence of objects?

Pool: Typically not. A pool is about saving the cost of object creation, so all the objects are kept in memory (reading from disk would defeat the purpose).

XFactory: Yes, XFactory is about saving the cost of performing complex calculations, so storing pre-calculated objects on disk makes sense.  As a result XFactory needs to deal with the typical problems of persistent storage; e.g. at initialization, it needs to connect to persistent storage, obtain from it the metadata about which objects are currently available there, and be ready to load them into memory if requested. And object may be in one of three states: “doesn’t exist”, “exists on disk”, “exists in memory”. While XFactory is running, the state may change only in one direction (to the right in this sequence).

In summary, the pool's complexity is in items 1, 2, 4, 6, and possibly 5, 7, 8. The XFactory complexity is in items 3, 6, 9. The only overlap is item 6, and it’s really not the core function of either pool or XFactory, but rather a constraint on the design that is common to any pattern that needs to work in a multithreaded environment.


答:
Tcl has a long history of supporting extensible syntax. For example, here's the implementation of a loop that iterates three variables (until stopped) over the cardinals, their squares and their cubes:

```<code>proc loopCard23 {cardinalVar squareVar cubeVar body} {
    upvar 1 $cardinalVar cardinal $squareVar square $cubeVar cube

    # We borrow a 'for' loop for the implementation...
    for {set cardinal 0} true {incr cardinal} {
        set square [expr {$cardinal ** 2}]
        set cube [expr {$cardinal ** 3}]

        uplevel 1 $body
    }
}
</code>```

That would then be used like this:

```<code>loopCard23 a b c {
    puts "got triplet: $a, $b, $c"
    if {$c > 400} {
        break
    }
}
</code>```

This sort of technique is used extensively in Tcl programming, and the key to doing it sanely are the upvar and uplevel commands (upvar binds a named variable in another scope to a local variable, and uplevel runs a script in another scope: in both cases, the 1 indicates that the scope in question is the caller's). It's also used a lot in code that couples with databases (running some code for each row in a result set), in Tk for GUIs (for doing binding of callbacks to events), etc.

However, that's only a fraction of what is done. The embedded language doesn't even need to be Tcl; it can be virtually anything (as long as it balances its braces — things get syntactically horrible if that's not true — which is the enormous majority of programs) and Tcl can just dispatch to the embedded foreign language as necessary. Examples of doing this include embedding C to implement Tcl commands and the equivalent with Fortran. (Arguably, all Tcl's built-in commands are done this way in a sense, in that they're really just a standard library and not the language itself.)

Body:
Tcl has a long history of supporting extensible syntax. For example, here's the implementation of a loop that iterates three variables (until stopped) over the cardinals, their squares and their cubes:

proc loopCard23 {cardinalVar squareVar cubeVar body} {
    upvar 1 $cardinalVar cardinal $squareVar square $cubeVar cube

    # We borrow a 'for' loop for the implementation...
    for {set cardinal 0} true {incr cardinal} {
        set square [expr {$cardinal ** 2}]
        set cube [expr {$cardinal ** 3}]

        uplevel 1 $body
    }
}

That would then be used like this:

loopCard23 a b c {
    puts "got triplet: $a, $b, $c"
    if {$c > 400} {
        break
    }
}

This sort of technique is used extensively in Tcl programming, and the key to doing it sanely are the upvar and uplevel commands (upvar binds a named variable in another scope to a local variable, and uplevel runs a script in another scope: in both cases, the 1 indicates that the scope in question is the caller's). It's also used a lot in code that couples with databases (running some code for each row in a result set), in Tk for GUIs (for doing binding of callbacks to events), etc.

However, that's only a fraction of what is done. The embedded language doesn't even need to be Tcl; it can be virtually anything (as long as it balances its braces — things get syntactically horrible if that's not true — which is the enormous majority of programs) and Tcl can just dispatch to the embedded foreign language as necessary. Examples of doing this include embedding C to implement Tcl commands and the equivalent with Fortran. (Arguably, all Tcl's built-in commands are done this way in a sense, in that they're really just a standard library and not the language itself.)


问:
Differences between symfony 2 and 1?
I'm starting symfony and interested in learning where symfony is coming from. In terms of it's architectural challenges.

What are the architectural or philosophical differences between symfony 2 and 1?

What changes make it so different from the other point version?

答:
There is a cookbook entry explaining the differences in depth.

One of the most important differences is code organisation. The bundles (which replace and enhance the idea of Sy1 plugins) are an excellent way of sharing code between modules / applications, helping you to create one strong backend and multiple frontends of your system. Even the public assets are now bundle-dependent, and not application-dependent.

The latest Sy2 comes with a great dependency management, Composer. It is the most intuitive way of reusing code from other sources and focusing solely on the development of your specific application logic / backend.

Title: Differences between symfony 2 and 1?


答:
Boo lets you customize the language heavily at compile-time through syntactic macros.

Boo has an "extensible compiler pipeline". That means the compiler can call your code to do AST transformations at any point during the compiler pipeline. As you know, things like Java's Generics or C#'s Linq are just syntax transformations at compile time, so this is quite powerful.

Compared to Lisp, the main advantage is that this works with any kind of syntax. Boo is using a Python-inspired syntax, but you could probably write an extensible compiler with a C or Pascal syntax. And since the macro is evaluated at compile time, there's no performance penalty.

Downsides, compared to Lisp, are:

Working with an AST is not as elegant as working with s-expressions

Since the macro is invoked at compile time, it doesn't have access to runtime data.

For example, this is how you might implement a new control structure:

```<code>macro repeatLines(repeatCount as int, lines as string*):
    for line in lines:
        yield [| print $line * $repeatCount |]
</code>```

usage:

```<code>repeatLines 2, "foo", "bar"
</code>```

which then gets translated, at compile time, to something like:

```<code>print "foo" * 2
print "bar" * 2
</code>```

(Unfortunately, Boo's online documentation is always hopelessly outdated and doesn't even cover advanced stuff like this. The best documentation for the language I know is this book: http://www.manning.com/rahien/)

Body:
Boo lets you customize the language heavily at compile-time through syntactic macros.

Boo has an "extensible compiler pipeline". That means the compiler can call your code to do AST transformations at any point during the compiler pipeline. As you know, things like Java's Generics or C#'s Linq are just syntax transformations at compile time, so this is quite powerful.

Compared to Lisp, the main advantage is that this works with any kind of syntax. Boo is using a Python-inspired syntax, but you could probably write an extensible compiler with a C or Pascal syntax. And since the macro is evaluated at compile time, there's no performance penalty.

Downsides, compared to Lisp, are:

Working with an AST is not as elegant as working with s-expressions

Since the macro is invoked at compile time, it doesn't have access to runtime data.

For example, this is how you might implement a new control structure:

macro repeatLines(repeatCount as int, lines as string*):
    for line in lines:
        yield [| print $line * $repeatCount |]

usage:

repeatLines 2, "foo", "bar"

which then gets translated, at compile time, to something like:

print "foo" * 2
print "bar" * 2

(Unfortunately, Boo's online documentation is always hopelessly outdated and doesn't even cover advanced stuff like this. The best documentation for the language I know is this book: http://www.manning.com/rahien/)


问:
What is the correct order to read these books?
I'm a junior C# developer, I learned at home and now I got my first job :)

I want to buy these books. But what is the correct order to read these books?

Code Complete: A Practical Handbook of Software Construction

Clean Code: A Handbook of Agile Software Craftsmanship

Pragmatic Programmer

答:
I'm also reading those books, here's my order:

Clean Code

Pragmatic Programer

Code Complete


答:
The evaluation Mathematica is based on pattern matching and replacement. That allows you to create your own control structures, change existing control structures or change the way expressions are evaluated. For example, you could implement "fuzzy logic" like this (a bit simplified):

```<code>fuzzy[a_ && b_]      := Min[fuzzy[a], fuzzy[b]]
fuzzy[a_ || b_]      := Max[fuzzy[a], fuzzy[b]]
fuzzy[!a_]           := 1-fuzzy[a]
If[fuzzy[a_], b_,c_] := fuzzy[a] * fuzzy[b] + fuzzy[!a] * fuzzy[c]
</code>```

This overrides the evaluation for the predefined logical operators &&,||,! and the built-in If clause.

You can read these definitions like function definitions, but the real meaning is: If an expression matches the pattern described on the left side, it's replaced with the expression on the right side. You could define your own If-clause like this:

```<code>myIf[True, then_, else_] := then
myIf[False, then_, else_] := else
SetAttributes[myIf, HoldRest]
</code>```

SetAttributes[..., HoldRest] tells the evaluator that it should evaluate the first argument before the pattern matching, but hold evaluation for the rest until after the pattern has been matched and replaced.

This is used extensively inside the Mathematica standard libraries to e.g. define a function D that takes an expression and evaluates to its symbolic derivative.

Body:
The evaluation Mathematica is based on pattern matching and replacement. That allows you to create your own control structures, change existing control structures or change the way expressions are evaluated. For example, you could implement "fuzzy logic" like this (a bit simplified):

fuzzy[a_ && b_]      := Min[fuzzy[a], fuzzy[b]]
fuzzy[a_ || b_]      := Max[fuzzy[a], fuzzy[b]]
fuzzy[!a_]           := 1-fuzzy[a]
If[fuzzy[a_], b_,c_] := fuzzy[a] * fuzzy[b] + fuzzy[!a] * fuzzy[c]

This overrides the evaluation for the predefined logical operators &&,||,! and the built-in If clause.

You can read these definitions like function definitions, but the real meaning is: If an expression matches the pattern described on the left side, it's replaced with the expression on the right side. You could define your own If-clause like this:

myIf[True, then_, else_] := then
myIf[False, then_, else_] := else
SetAttributes[myIf, HoldRest]

SetAttributes[..., HoldRest] tells the evaluator that it should evaluate the first argument before the pattern matching, but hold evaluation for the rest until after the pattern has been matched and replaced.

This is used extensively inside the Mathematica standard libraries to e.g. define a function D that takes an expression and evaluates to its symbolic derivative.


问:
Is it bad practice to output from within a function?
For example, should I be doing something like:

```<code><?php
function output_message($message,$type='success') {
  ?>
  <p class="<?php echo $type; ?>"><?php echo $message; ?></p>
  <?php
}
output_message('There were some errors processing your request','error');
?>
</code>```

or

```<code><?php
function output_message($message,$type='success') {
  ob_start();
  ?>
  <p class="<?php echo $type; ?>"><?php echo $message; ?></p>
  <?php
  return ob_get_clean();
}
echo output_message('There were some errors processing your request','error');
?>
</code>```

I understand they both achieve the same end result, but are there benefits doing one way over the other? Or does it not even matter?

答:
As longs as it's clear from the name, comments and signature of the function that its purpose is to generate output, there's nothing wrong with it.

What's not good is to have output generation as a side effect of a function that also does something else (like compute and return some data, or write a file), because that's a flagrant violation of the single responsibility principle.


答:
If the purpose of the function is to output_message() then I would expect the calling of the function to actually output the message.

If on the other hand, the function was called generate_message() then I would not expect it to do the outputting:

```<code><?php
function generate_error_message($message,$type='success') {
  ob_start();
  ?>
  <p class="<?php echo $type; ?>"><?php echo $message; ?></p>
  <?php
  return ob_get_clean();
}

echo generate_error_message('There were some errors processing your request','error');
?>
</code>```

But I certainly agree with Michael that a function should only generate output related to its function

Title: Is it bad practice to output from within a function?

Body:
For example, should I be doing something like:

```<code><?php
function output_message($message,$type='success') {
  ?>
  <p class="<?php echo $type; ?>"><?php echo $message; ?></p>
  <?php
}
output_message('There were some errors processing your request','error');
?>
</code>```

or

```<code><?php
function output_message($message,$type='success') {
  ob_start();
  ?>
  <p class="<?php echo $type; ?>"><?php echo $message; ?></p>
  <?php
  return ob_get_clean();
}
echo output_message('There were some errors processing your request','error');
?>
</code>```

I understand they both achieve the same end result, but are there benefits doing one way over the other? Or does it not even matter?

Body:
If the purpose of the function is to output_message() then I would expect the calling of the function to actually output the message.

If on the other hand, the function was called generate_message() then I would not expect it to do the outputting:

<?php
function generate_error_message($message,$type='success') {
  ob_start();
  ?>
  <p class="<?php echo $type; ?>"><?php echo $message; ?></p>
  <?php
  return ob_get_clean();
}

echo generate_error_message('There were some errors processing your request','error');
?>

But I certainly agree with Michael that a function should only generate output related to its function


答: It's not quite there yet but Miguel de Icaza, a guy who knows a thing or two about the Davlik VM says "F# for droid is on their list of things to do." So I'd say an officialish package is coming.  </p>

Title: Functional Languages that compile to Android's Dalvik VM?

Body:
I have a software problem that fits the functional approach to programming, but the target market will be on the Android OS.  I ask because there are functional languages that compile to Java's VM, but Dalvik bytecode != Java bytecode.

Alternatively, do you know if the dx utility can intelligently convert the .class files generated from functional languages like Scala?

Edit:
In order to add a bit more helpfulness to the community, and also to help me choose better, can I refine the question a bit?

Have you used any alternate languages with Dalvik?  Which ones?

What are some "gotchas" (problems) that I might run into?

Is performance acceptable?  By that, I mean the application still feels responsive to the user.

I've never done mobile phone development, but I grew up on constrained devices and I'm under no illusion that there is a cost to using non-standard languages with the platform.  I just need to know if the cost is such that I should shoe-horn my approach into default language (i.e. apply functional principles in the OOP language).


问:
Useful programming languages for hardware programming
I am thinking to take the next semester a course called "Digital systems architecture", and I know that we need to program micro-controllers with several programming languages such as C, C++, verilog, and VHDL. I want to be prepared to take that course, but I need to know if I need to study deeper these languages.

At this moment, I have taken one course in basic Java dealing with basic methods, data types, loop structures, vectors, matrices, and GUI programing. Must I study deeper Java and then go with C, and C++? Besides, I know basic verilog and VHDL.

答:
During my studies, we used C and VHDL, but C was by far the more prominent language used. And the advantage of learning C is of course obvious even beyond hardware programming. So that's what I recommend. When you learn C very well, it should give you no trouble to learn Java and C++ later on - it's just about learning the OOP aspects of both, mostly. After learning C, you will already have a good grasp of the main principles of programming.

And if our professors are to be trusted, the majority of embedded hardware is still programmed with plain old C, so it should be more than enough to land a job. Then you can branch out to either more sophisticated systems still in C, or more modern (and more rare, would you believe?) programming with C++ and others. The majority of embedded hardware is so simple, that using 32-bit MCUs would be incredibly overkill and a waste of revenue and resources.

But of course, it depends on your interest. If you want to program modern hardware, like GPUs, SSD controllers and such, then C++ will possibly kickstart you closer - although Assembly is most likely what you will be using, depending on how close to the "core" you will get with the hardware.

As for Java, C++ and similar, perhaps multimedia hardware (DVD/BluRay players, modern TVs, etc) is the field that uses those languages.


问:
Wrapping REST based Web Service
I am designing a system that will be running online under Microsoft Windows Azure. One component is a REST based web service which will really be a wrapper (using proxy pattern) which calls the REST web services of a business partner, which has to do with BLOB storage (note: we are not using azure storage). The majority of the functionality will be taking a request, calling our partner web service, receiving the request and then passing that back to the client.

There are a number of reasons for doing this, but one of the big ones is that we are going to support three clients: our desktop application (win and mac), mobile apps (iOS), and a web front end. Having a single API which we then send to our partner protects us if that partner ever changes.

I want our service to support both JSON and XML for the data transfer format, JSON for web and probably XML for the desktop and mobile (we already have an XML parser in those products). Our partner also supports both of these formats.

I was planning on using ASP.NET MVC 4 with the Web API. As I design this, the thing that concerns me is the static type checking of C#. What if the partner adds or removes elements from the data? We can probably defensively code for that, but I still feel some concern. Also, we have to do a fair amount of tedious coding, to setup our API and then to turn around and call our partner’s API. There probably is not much choice on it though. But, in the back of my mind I wonder if maybe a more dynamic language would be a better choice.

I want to reach out and see if anybody has had to do this before, what technology solutions they have used to (I am not attached to this one, these days Azure can host other technologies), and if anybody who has done something like this can point out any issues that came up. Thanks!

Researching the issue seems to only find solutions which focus on connecting a SOAP web service over a proxy server, and not what I am referring to here.

Note: Cross posted (by suggestion) from https://stackoverflow.com/questions/11906802/wrapping-rest-based-web-service

Thank you!

答:
I've built a rest service wrapper or two.

You shouldn't really have to worry about the partner adding fields -- the serialization will move past that with ease in most cases. Well, unless you shoot yourself in the foot and start using schema validation on the returns from your partner. Removing fields won't cause a crash at the point of import in most cases but it can cause some interesting effects down the line. The only crash issue is if your partner starts changing types on you -- such as deciding an identifier is really a string not an integer. That said, it is pretty well understood how to version APIs in 2012. Unless you are facebook, you don't randomly change things on your partner. If the blob storage is one of the 3 likely candidates then I'd expect the API to be nearly set in stone -- there are enough clients out in the wild for those that they could not change without ruining a few million hipsters days.

That said, how I would build an early warning system for this sort of scenarios would be to write my wrapper library in a test-driven way, making sure to cover the deserialization parts really well and with fine-grained detail. Then use a CI server to automatically run the service tests on said library every other hour or so. If the tests are good, you will have a very good idea what changed, when and how it hurts and perhaps how to fix.

But I really wouldn't worry about this too much given decent instrumentation and error handling in your product.

Title: Wrapping REST based Web Service


问:
Relicense BSD 2/3-clause code to GPL
Suppose I release some source code under the new BSD license. Is it allowed for someone else to take this code, make modifications to it and distribute it under the terms of the GPL? From Wikipedia:

Many of the most common free software
  licenses, such as the original MIT/X
  license, BSD licenses (in the current
  2-clause form), and the LGPL, are
  "GPL-compatible". That is, their code
  can be combined with a program under
  the GPL without conflict (the new
  combination would have the GPL applied
  to the whole). However, some free/open
  source software licenses are not
  GPL-compatible.

I'm assuming this implies that one can relicense new-BSD licensed code to GPL?

答:
Sorry but most of you are wrong.

Licensing and ownership are two different things.
You cannot re-license something you do not own. Is not your decision to make.

The owner is the copyright holder, not you. Thus you cannot re-license their work. As you do not own their work, you are only licensing it. That is, the owner is allowing you to use it. He/She is not giving ownership to you.

It will be ridiculous to think, for example, that the original author (or ANYONE that obtained the BSD code) has to follow the GPL to use the original code just because you decided to use THEIR CODE on a GPL project.

However you can license into GPL YOUR OWN code. And then, THAT PART, not the original one, is under the GPL. As the original author did not put the work on GPL and as you are ONLY licensing and NOT OWNING the original work.

You can use BSD licensed code on your GPL code (as BSD allows you this, as long as you follow BSD terms, and one is NOT TO REMOVE the license from the copies), but you cannot simply re-license the whole thing, as you do not own it. Again, is not your decision to make. If however you want to use a third party GPL code with BSD code. Then the problem will be complying with the GPL part.

Title: Relicense BSD 2/3-clause code to GPL


问:
Storing Projects on Google Drive (Cloud)
I've started using Google Drive for my cloud needs and backing up pretty much everything. I've got the app installed so it auto-sync's all my content in most things.

My question is this, I am currently coding for iOS (although this applies to any coding project) and am split on storing my project files on Google Drive while using sync. My theory is that if I did use it, I'd never have to worry about system crashes or lost code before backups, but if I do use it it will be sync'ing a-lot and I thought there might be problems with it detecting changes and trying to sync for example half way through compiling.

Bandwidth isn't an issue as I have fast connection and unlimited monthly allowance.

Has anyone ever used this, or similar cloud-based sync'ing (dropbox etc) for this and knows whether it works or not or whether there are any potential problems etc.

答:
Cloud-based file syncing is great for pictures of your cat.

Cloud-based scm such as github or bitbucket are what you should use for code. They have all the advantages of cloud file storage plus nearly magical abilities to version, compare and merge source files.

Personally I'm partial to bitbucket as you get free unlimited private and public repositories  and mercurial is much more approachable than git.


问:
Programming languages with a Lisp-like syntax extension mechanism
I have only a limited knowledge of Lisp (trying to learn a bit in my free time) but as far as I understand Lisp macros allow to introduce new language constructs and syntax by describing them in Lisp itself. This means that a new construct can be added as a library, without changing the Lisp compiler / interpreter.

This approach is very different from that of other programming languages. E.g., if I wanted to extend Pascal with a new kind of loop or some particular idiom I would have to extend the syntax and semantics of the language and then implement that new feature in the compiler.

Are there other programming languages outside the Lisp family (i.e. apart from Common Lisp, Scheme, Clojure (?), Racket (?), etc) that offer a similar possibility to extend the language within the language itself?

EDIT

Please, avoid extended discussion and be specific in your answers. Instead of a long list of programming languages that can be extended in some way or another, I would like to understand from a conceptual point of view what is specific to Lisp macros as an extension mechanism, and which non-Lisp programming languages offer some concept that is close to them.

答:
If you're looking for languages that are extendable, you ought to take a look at Smalltalk.

In Smalltalk, the only way to program is to actually extend the language. There is no difference between the IDE, the libraries or the language itself. They're all so entwined that Smalltalk is often referred to as an environment rather than as a language.

You don't write stand-alone applications in Smalltalk, you extend the language-environment instead.

Check out http://www.world.st/ for a handful of resources and information.

I'd like to recommend Pharo as the dialect of entry to the world of Smalltalk: http://pharo-project.org

Hope it helped!


问:
Is it a bad idea to ask an interviewer what the greatest strength and weakness of their development team is?
I was wondering if this was a good question to ask a possible employer when interviewing for a developer position:

What is the greatest strength and weakness of your development team?

We all get this question when we are in an interview, so why not ask them in return? I think it is a very good question because we could find out about the team, and how this strength or weakness could affect us, but I don't want to annoy the interviewer.

Is there any downside to asking this question when interviewing for a developer position?

答:
One of my stock questions for my possible future employer is "why do you love working for your company?"

It aims at getting the same kind of information, but in a positive and optimistic way.  In great places to work, you'll find that often your interviewer will start gushing all kinds of great information you really want to know to make your decision!


问:
Reuse the data CRUD methods in data access layer, but they are updated too quickly
I agree that we should put CRUD methods in a data access layer， However, in my current project I have some issues.

It is a legacy system, and there are quite a lot CRUD methods in some concrete manager classes.

People including me seem to just add new methods to it, rather than reuse the existing methods.

Because

We don't know whether the existing method is what we need

Even if we have source code, do we really need read other's code then make decision?

It is updated too quickly. Do not have time get familiar with the DAO API.

Back to the question, how do you solve that in your project? If we say "reuse", it really needs to be reusable rather than just an excuse.

答:
The main problem would seem to be that the legacy interfaces are not understood and not trusted.  It's not possible to solve this problem by ignoring it - and adding more members ad-hoc is actively making it worse.

The bottom line is that interfaces to your classes should be clear, small, trusted, well-documented, and ideally only about a single responsibility (refer to the Single Responsibility Principle).

Techniques like refactoring can be used to move towards that ideal goal.  Remember: it will take conscious effort to improve the situation.


答:
Assuming that your organization has the right for to access and change the code, the right thing to do is to:

Plan for missing activities in your project such as: source control, locating missing code, learning current system, etc.

Find the source code for the system you are changing. Unless the application is trivial, it is most probably going to be useful specially if it is still in production.

Study the schema and the source code well and plan to re-use. You may find information you don't know such as filed dependencies that are not obvious or special business rules.

Don't write new code that is like the old code unless there is a major issue with the old code. You need to have a clear policy as why there are 2 different classes for Customer for example, otherwise, maintenance and testing will be hell.

I don't understand your point (#3).

The only valid excuses to not re-use existing system's code, INMO, is if you are migrating the system to use a new framework or can't access the code for a technical or legal reason. A system must have internal order and proper structure, it can't be a quality system if it looks like a college student's room!

Title: Reuse the data CRUD methods in data access layer, but they are updated too quickly

Body:
I agree that we should put CRUD methods in a data access layer， However, in my current project I have some issues.

It is a legacy system, and there are quite a lot CRUD methods in some concrete manager classes.

People including me seem to just add new methods to it, rather than reuse the existing methods.

Because

We don't know whether the existing method is what we need

Even if we have source code, do we really need read other's code then make decision?

It is updated too quickly. Do not have time get familiar with the DAO API.

Back to the question, how do you solve that in your project? If we say "reuse", it really needs to be reusable rather than just an excuse.


问:
What is preferred for file I/O in Java?
Of the three

 BufferedReader/Writer

 Binary Streams

 Channels

which is more preferred in real life for file I/O in Java and why?

I prefer channels for binary data to be put into file or read from and BufferedReader/Writer for String data

答:
which is more preferred in real life for file I/O in Java and why?

It should really be a matter of function rather than preference.

You use Readers and Writers for character oriented data (which requires encoding and decoding), Input/OutputStreams for byte-oriented data, and Binary streams if the data encodes binary data.

You use the BufferedXxx classes if you need to I/O at the granularity of a character or byte.  They are a simple way to avoid the serious performance problems that can occur if you do lots of byte-at-a-time read and write syscalls.

If you only do I/O by reading / writing large chunks, then the BufferedXxx classes might might actually reduce throughput a bit.  You can either use plain readers/writers/streams (with big char[] or byte[] buffers), or Channels and XxxBuffers.  The latter are potentially faster, but the APIs are more awkward.

You use Channels if you need low overheads, and/or do specialised things such as "selecting" from multiple streams, scatter / gather, and memory mapped file access.

As you can see, the different APIs is designed for different purposes.  In some use-cases there is overlap, in others only one API is fit for the purpose.

The problem with developing a "preference" for one style of I/O over another is that it leads to bad software; i.e. either code that is inefficient where I/O efficiency is needed, or overly complicated where I/O efficiency should not be a concern.

Title: What is preferred for file I/O in Java?


问:
If I define a property to prototype appears in the constructor of object, why?
I took the example from this question modified a bit:
What is the point of the prototype method?

```<code>function employee(name,jobtitle,born)
{
this.name=name;
this.jobtitle=jobtitle;
this.born=born;
this.status="single"
}
employee.prototype.salary=10000000;
var fred=new employee("Fred Flintstone","Caveman",1970);
console.log(fred.salary);
fred.salary=20000;
console.log(fred.salary)
</code>```

And the output in console is this:

What is the difference salary is in constructor but I still can access it with fred.salary, how can I see if is in constructor from code, status is still employee property how can I tell for example if name is the one of employee or has been touch by initialization?

Why is salary in constructor, when name,jobtitle,born where "touched" by employee("Fred Flintstone","Caveman",1970); «constructor»?

答:
By setting the prototype, you are just making an object to be shared with other instances of the same type. ie,

```<code>var liz = new employee('Elizabeth','Teacher',1980);
var jane = new employee('Jane','unknown',1981);
</code>```

liz.salary is same as jane.salary, even the underlying memory will be the same.

but when you set the salary of an instance, you are not changing the salary variable in the prototype, but you are defining a new property unique for that instance. so, fred.salary = 20000 will just hide the salary attribute of the prototype.

so fred.salary will make javascript engine to look for salary in the fred instance tree, upon which it will take the direct property of that instance.
while liz.salary will resolve to the property in the prototype.

I hope now the console output make some sense.

Body:
By setting the prototype, you are just making an object to be shared with other instances of the same type. ie,

var liz = new employee('Elizabeth','Teacher',1980);
var jane = new employee('Jane','unknown',1981);

liz.salary is same as jane.salary, even the underlying memory will be the same.

but when you set the salary of an instance, you are not changing the salary variable in the prototype, but you are defining a new property unique for that instance. so, fred.salary = 20000 will just hide the salary attribute of the prototype.

so fred.salary will make javascript engine to look for salary in the fred instance tree, upon which it will take the direct property of that instance.
while liz.salary will resolve to the property in the prototype.

I hope now the console output make some sense.


问:
Resurrecting a 5,000 line test plan that is a decade old
I am currently building a test plan for the system I am working on.  The plan is 5,000 lines long and about 10 years old.  The structure is like this:

```<code>1. test title
   precondition: some W needs to be set up, X needs to be completed
   action: do some Y
   postcondition: message saying Z is displayed
2. ...
</code>```

What is this type of testing called ?  Is it useful ?

It isn't automated.. the tests would have to be handed to some unlucky person to run through and then the results would have to be given to development.  It doesn't seem efficient.  Is it worth modernising this method of testing (removing tests for removed features, updating tests where different postconditions happen, ...) or would a whole different approach be more appropriate ?  We plan to start unit tests but the software requires so much work to actually get 'units' to test - there are no units at present !  Thank you.

答:
You may still use that file to test and there are benefits of human testing of UI part of the application. However, you may also look at automation part where you have couple choices.

I would look at alternative file or test objects input/output testing, if it is hard (even not possible) to add unit tests to your inherited project. Basically, you need to prepare input test files/objects to feed your program and compare the output with the one that has expected results. This matching mechanism might help to discover them.

You may use the existing structure of testing to build your input/output files or objects. In addition, because this code is 1o years old,  i would double check this tests with business analyst or the subject matter expert to verify the tests, and cover the all important business processes that application should provide.

Although it may look like not the best way of automation, but it is extensively used in old medical billing systems.


答:
From what you write, it looks like a list of test cases for manual integration testing / GUI testing. It might not be efficient, but any tests are better than no tests and any plan is better than no plan, so you might as well start with what you have.

Certainly you would need to review the plan and update it to cover changes made to the software over time. Obviously having obsolete test cases for nonexistant functionality would be counterproductive.

Keep in mind that even though this test plan was written with manual testing in mind, you might as well automate the process. Research automated testing tools available for your project/platform. If it's a web application, look into Selenium. There are solutions for desktop applications too, but I'm not familiar with any to make a suggestion. Even though it may be a time consuming task, automating these tests, you may find it easier then introducing unit tests. You may also find it useful to have these automated tests when you get around to refactoring the project, as you can use them to validate your changes while you're adding the unit tests.

Title: Resurrecting a 5,000 line test plan that is a decade old

Body:
I am currently building a test plan for the system I am working on.  The plan is 5,000 lines long and about 10 years old.  The structure is like this:

```<code>1. test title
   precondition: some W needs to be set up, X needs to be completed
   action: do some Y
   postcondition: message saying Z is displayed
2. ...
</code>```

What is this type of testing called ?  Is it useful ?

It isn't automated.. the tests would have to be handed to some unlucky person to run through and then the results would have to be given to development.  It doesn't seem efficient.  Is it worth modernising this method of testing (removing tests for removed features, updating tests where different postconditions happen, ...) or would a whole different approach be more appropriate ?  We plan to start unit tests but the software requires so much work to actually get 'units' to test - there are no units at present !  Thank you.


答:
Since the test is 10 years old and it talks about "message Z is displayed", I would call this UI Regression Testing - testing to see that recent changes haven't broken older UI functionality.

The only way to find out if the test is still useful is to do your best to test with it!  Automated application-(non-user)-interface testing is always a win and Selenium is really sharp, but the effort to maintain any automated UI test is often equal to or greater than the effort required to test manually every release.  The advantage of manual testing is that (in theory) you can be tolerant of visual UI changes on a screen with unchanged functionality.  In fact, this is exactly what you want to test for in the user-interface and exactly what makes automated testing report false positives.

I find the hardest part of writing a UI test is getting the right amount of detail so that testers stay alert to the experience a user would be having with the system instead of focusing so much on the test-plan details that they miss the bugs.  I haven't closed that question yet, but the sense I'm getting is that it may be useful to have a Selenium test in addition to a manual UI test.  So that the details are tested by Selenium and the over-all experience is still tested by humans who can test it better without being bogged down by an over-detailed test plan.

Every kind of UI testing has its problems.  There is no substitute for an interested person who really wants to find bugs.


问:
TDD, BDD or both?
I'm a little bit confused about BDD. I'm doing TDD currently.

My question is whether BDD is complementary to TDD or it's a whole new thing and my team should do both TDD and BDD? Or is it enough to do just one or the other?

答:
By definition, BDD is based upon TDD and is a refinement / extension / specialization of the latter.

is it enough to do just one or the other?

According to the above, you can't do BDD without TDD.

In general, there is no one-size-fits-all answer: do what suits your team and your project the best. Feel free to experiment with new ideas, pick what works and drop or change what doesn't.

Moreover, this is not an all or nothing question: you can do TDD enhanced with specific ideas from BDD which you feel are a valuable addition to your process. For example, I adapted the "should" naming convention of unit tests in my practice because I find it makes my unit tests more readable and expressive.

Title: TDD, BDD or both?


问:
Ideal programming language learning sequence?
What do you think? What is the ideal programming language learning sequence which will cover most of the heavily used languages and paradigms today as well as help to grasp common programming basics, ideas and practices?
You can even suggest learning sequence for paradigms rather than languages.

N.B. : This is port of the question I asked in stackoverflow and was closed for being subjective and argumentative.

答:
The one you need now

The one you need next

The one you need after that

Seriously, I may have learnt BASIC, COBOL, Fortran, Forth, Pascal and Prolog in my time, but I've never particularly needed to use them and I can't really see any way in which they've influenced my use of other languages, except perhaps misapplying paradigms from one in another. It took me ages to unlearn BASIC enough to actually write structured Pascal, a couple of years to stop writing Pascal code in C, and another couple of years to actually grok OOP when I started using Objective-C and Java. On the other hand, since I've been working (almost) exclusively in OO languages I've been able to concentrate on improving my use of OO languages, without trying to make them look like Scheme or PostScript.


答:
TeX is totally missing from the list. You all know it, right? It looks something like this:

```<code>Some {\it ``interesting''} example.
</code>```

… except that you can redefine the syntax without restrictions. Every (!) token in the language can be assigned a new meaning. ConTeXt is a macro package which has replaced curly braces with square braces:

```<code>Some \it[``interesting''] example.
</code>```

The more common macro package LaTeX also redefines the language for its purposes, e.g. adding the \begin{environment}…\end{environment} syntax.

But it doesn’t stop there. Technically, you could just as well redefine the tokens to parse the following:

```<code>Some <it>“interesting”</it> example.
</code>```

Yes, absolutely possible. Some packages use this to define small domain-specific languages. For instance, the TikZ package defines a concise syntax for technical drawings, which allows the following:

```<code>\foreach \angle in {0, 30, ..., 330}
  \draw[line width=1pt] (\angle:0.82cm) -- (\angle:1cm);
</code>```

Furthermore, TeX is Turing complete so you can literally do everything with it. I have never seen this used to its full potential because it would be pretty pointless and very convoluted but it’s entirely possible to make the following code parseable just by redefining tokens (but this would probably go to the physical limits of the parser, due to the way it’s built):

```<code>for word in [Some interesting example.]:
    if word == interesting:
        it(word)
    else:
        word
</code>```

Body:
TeX is totally missing from the list. You all know it, right? It looks something like this:

Some {\it ``interesting''} example.

… except that you can redefine the syntax without restrictions. Every (!) token in the language can be assigned a new meaning. ConTeXt is a macro package which has replaced curly braces with square braces:

Some \it[``interesting''] example.

The more common macro package LaTeX also redefines the language for its purposes, e.g. adding the \begin{environment}…\end{environment} syntax.

But it doesn’t stop there. Technically, you could just as well redefine the tokens to parse the following:

Some <it>“interesting”</it> example.

Yes, absolutely possible. Some packages use this to define small domain-specific languages. For instance, the TikZ package defines a concise syntax for technical drawings, which allows the following:

\foreach \angle in {0, 30, ..., 330}
  \draw[line width=1pt] (\angle:0.82cm) -- (\angle:1cm);

Furthermore, TeX is Turing complete so you can literally do everything with it. I have never seen this used to its full potential because it would be pretty pointless and very convoluted but it’s entirely possible to make the following code parseable just by redefining tokens (but this would probably go to the physical limits of the parser, due to the way it’s built):

for word in [Some interesting example.]:
    if word == interesting:
        it(word)
    else:
        word


答:
This looks a lot like the system tests we used to use about fifteen years ago.  Most of the ones we used couldn't be automated, because they had preconditions like configuring specific hardware (this was for telecom switches) or had test steps like "while data is transferring, apply a 100mV square wave signal to the TxD line and sweep the frequency from 50 to 120Hz repeatedly".

I'd recommend you automate as much as you can, but don't expect to eliminate everything on your test plan.  Some degree of manual testing should be done for any interactive system.


问:
Can each mobile app have its own client account for payments? (Windows Phone, Android and iPhone)
My company has many clients wanting mobile applications and having the payments come into our account and then sorting the payments would be a real pain.
So can a company have a main account to publish applications (free and chargeable) and still have some sort of client account for each app (so they could view sales and receive full payment directly)?

I would like to know for Windows, Android and Apple please.

答:
For maintainability and ease of communication back with customers, i am strongly recommending to create different accounts for FREE and commercial apps that you are publishing to marketplace.

At least in Windows marketplace, if you keep adding your apps from one account, you may end-up with hundreds of feedback and emails without a glue (do i need to urgently support this or not?) from where (paid /free app) it comes from.


问:
How to build MVC Views that work with polymorphic domain model design?
This is more of a "how would you do it" type of question.

The application I'm working on is an ASP.NET MVC4 app using Razor syntax.

I've got a nice domain model which has a few polymorphic classes, awesome to work with in the code, but I have a few questions regarding the MVC front-end.

Views are easy to build for normal classes, but when it comes to the polymorphic ones I'm stuck on deciding how to implement them.

The one (ugly) option is to build a page which handles the base type (eg. IContract) and has a bunch of if statements to check if we passed in a IServiceContract or ISupplyContract instance. Not pretty and very nasty to maintain.

The other option is to build a view for each of these IContract child classes, breaking DRY principles completely. Don't like doing this for obvious reasons.

Another option (also not great) is to split the view into chunks with partials and build partial views for each of the child types that are loaded into the main view for the base type, then deciding to show or hide the partial in a single if statement in the partial. Also messy.

I've also been thinking about building a master page with sections for the fields that only occur in subclasses and to build views for each subclass referencing the master page. This looks like the least problematic solution? It will allow for fairly simple maintenance and it doesn't involve code duplication.

What are your thoughts? Am I missing something obvious that will make our lives easier? Suggestions?

答:
The solution we've used - where this is appropriate - is to use DisplayFor and EditFor

We have strongly typed display and edit templates so the base view is a nice, simple, clean iteration over a list of items and the templates handle the polymorphism.

One can argue about the suitability of building views over domain models - but that doesn't remove the requirement to be able to display a list of items that have are notionally the same (have a common root) but vary in detail and in the case we have this solved the problem very neatly without having to put any logic in the view

OwnerDisplayName: Johann de Swardt


答:
Actually, building individual views for each of the IContract classes would not be breaking DRY -- presumably they have some different info with different needs. You aren't repeating yourself, you are successfully using polymorphisim.

I had a somewhat similar conoundrum for a project MVC1 project -- before DisplayFor provided a pretty good built-in solution. We used MVC Contrib's RenderAction delegates to send the polymorphic object off to a specialized controller that was responsible for dispatching things to the appropriate rendering pipeline. The internals get a bit squirrely, but it has been a rock solid system for us for 3 years or more.

Title: How to build MVC Views that work with polymorphic domain model design?

Body:
This is more of a "how would you do it" type of question.

The application I'm working on is an ASP.NET MVC4 app using Razor syntax.

I've got a nice domain model which has a few polymorphic classes, awesome to work with in the code, but I have a few questions regarding the MVC front-end.

Views are easy to build for normal classes, but when it comes to the polymorphic ones I'm stuck on deciding how to implement them.

The one (ugly) option is to build a page which handles the base type (eg. IContract) and has a bunch of if statements to check if we passed in a IServiceContract or ISupplyContract instance. Not pretty and very nasty to maintain.

The other option is to build a view for each of these IContract child classes, breaking DRY principles completely. Don't like doing this for obvious reasons.

Another option (also not great) is to split the view into chunks with partials and build partial views for each of the child types that are loaded into the main view for the base type, then deciding to show or hide the partial in a single if statement in the partial. Also messy.

I've also been thinking about building a master page with sections for the fields that only occur in subclasses and to build views for each subclass referencing the master page. This looks like the least problematic solution? It will allow for fairly simple maintenance and it doesn't involve code duplication.

What are your thoughts? Am I missing something obvious that will make our lives easier? Suggestions?