问:
Should I bother learning about small or niche languages?
If you browse the code golf questions on StackExchange, you notice a ton of non-standard but real world (Eg not brain-f*ck) languages like F#, Scala, R, J and Clojure. Visiting their websites, some of the languages look interesting solving problems in whatever language your already using.

However there is coding in spare time, and coding for money. The closest thing we have to the truth on who uses a language is the TIOBE Index, which lists none of the above languages in the top 10-15. Which makes me wonder if I'll ever use them.

Should I even bother learning some of the small niche languages? It doesn't seem I would be making money, and some will probably fail anyway.

答:
The Sapir-Whorf Hypothesis.  It states, more or less, that what you can think of is limited by what you have the language to describe.  The consequence of this is that multi-lingual people are able to think in ways that single language speakers may not be able to.

Many people (myself included) think this holds true to programming as well.  Learning Lisp, for example, teaches you a whole new way of thinking about problems that you can apply to C# or Java or Python.  The more language paradigms you've learnt, the more tools will be in your mental toolbox, regardless of what language you're actually using.


问:
In REST is HATEOAS really about self-discovery or about navigation?
I'm trying to learn about REST and having problems with the concept of HATEOAS (Hypermedia As The Engine Of Application State).  What is it for?

It seems to me the majority of commenters on the web think that HATEOAS should be used by a client to discover how to use a RESTful web service.  And most seem to conclude that HATEOAS is not worth including in RESTful web services for one of two reasons:

1) HATEOAS only gives URLs but these are useless by themselves without knowing what methods can be used with each URL (eg HTTP GET, POST, PUT).  Since the additional information must be passed to the client out of band (eg via documentation) then there is no point in using HATEOAS;

2) Similar to (1) but takes it a step further:  The client can figure out what methods are applicable to a given URL by calling the HTTP OPTIONS method.  However, the client still needs out of band information, to describe the format of the data it must pass for, say, POST or PUT methods.  So we end up in the same place as (1) - HATEOAS isn't sufficient for a client to discover everything it needs to know, so why bother with it.

These arguments seem valid if HATEOAS is supposed to be used by a client to discover how to use a RESTful web service.  However, is that what HATEOAS is for?  From the few examples I've seen, it seems to me to be perfect for navigating through a web service - I've performed a certain action, now what are the valid actions I can perform next?  That seems to me to gel with the "Application State" part of HATEOAS but very few articles I've read talk of it in terms of navigation, almost all are about discovery.

So, is HATEOAS about discovering how to use a RESTful web service or is it really about navigation?

答:
@VoiceOfUnreason's answer suggests that HATEOAS is really just about links.  However, the Programmers StackExchange question @RobertHarvey linked to, What does HATEOAS offer for discoverability and decoupling besides ability to change your URL structure more or less freely?, suggests it's more complicated than that, and HATEOAS includes both using the OPTIONS method to determine which methods can be called on a resource, and defining a media type to specify the format of data in the request and the response.

One of the answers to that question ("What does HATEOAS offer...") includes a link to a blog post from Roy Fielding, who originally defined REST: REST APIs must be hypertext-driven.  Some snippets from that blog post:

A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types. Any effort spent describing what methods to use on what URIs of interest should be entirely defined within the scope of the processing rules for a media type (and, in most cases, already defined by existing media types). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]

A REST API must not define fixed resource names or hierarchies (an obvious coupling of client and server). Servers must have the freedom to control their own namespace. Instead, allow servers to instruct clients on how to construct appropriate URIs, such as is done in HTML forms and URI templates, by defining those instructions within media types and link relations. [Failure here implies that clients are assuming a resource structure due to out-of band information, such as a domain-specific standard, which is the data-oriented equivalent to RPC’s functional coupling].

A REST API should never have “typed” resources that are significant to the client. Specification authors may use resource types for describing server implementation behind the interface, but those types must be irrelevant and invisible to the client. The only types that are significant to a client are the current representation’s media type and standardized relation names. [ditto]

A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types that are appropriate for the intended audience (i.e., expected to be understood by any client that might use the API). From that point on, all application state transitions must be driven by client selection of server-provided choices that are present in the received representations or implied by the user’s manipulation of those representations. The transitions may be determined (or limited by) the client’s knowledge of media types and resource communication mechanisms, both of which may be improved on-the-fly (e.g., code-on-demand). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]

(As an aside: I get the impression from many blog posts that a lot of people see HATEOAS as sort of an optional extra to REST.  However, Roy Fielding's comments quoted above indicate HATEOAS is actually central to REST and you can't have a RESTful API without it.)

If anyone finds this answer useful please upvote @RobertHarvey's comment to my question above, the one that has the "What does HATEOAS offer..." link.

ContentLicense: CC BY-SA 3.0


问:
How useful is C's "true" sizing of variables?
One thing that always intuitively struck me as a positive feature of C (well, actually of its implementations like gcc, clang, ...) is the fact that it does not store any hidden information next to your own variables at runtime. By this I mean that if you for example wanted a variable "x" of the type "uint16_t", you could be sure that "x" will only occupy 2 bytes of space (and won't carry any hidden information like its type etc.). Similarly, if you wanted an array of 100 integers, you could be sure it is as big as 100 integers.

However, the more I am trying to come up with concrete use cases for this feature the more I am wondering if it actually has any practical advantages at all. The only thing I could come up with so far is that it obviously needs less RAM. For limited environments, like AVR chips etc., this is definitely a huge plus, but for everyday desktop / server use cases, it seems to be rather irrelevant. Another possibility I am thinking of is that it might be helpful / crucial for accessing hardware, or maybe mapping memory regions (for example for VGA output and the like) ... ?

My question: Are there any concrete domains that either can't or can only very cumbersomely be implemented without this feature?

P.S. Please tell me if you have a better name for it! ;)

答: You hit on one of the only reasons this is useful: mapping external data structures.  Those include memory-mapped video buffers, hardware registers, etc.  They also include data transmitted intact outside the program, like SSL certificates, IP packets, JPEG images, and pretty much any other data structure that has a persistent life outside the program.


问:
How do you test a selenium framework?
I have a very large selenium test framework I use to test a web application. It it built around a page-object pattern.

This week I fixed a bug in a low level piece of the framework, but it broke many other pieces that got built on top of this bug. I didn't have a good way to find these spots without running the full test suite of several thousand UI tests.

Since this isn't ideal, what strategy can I use to unit test new functionality and page-object modifications/additions to the framework?

答:
Quis custodiet ipsos custodes?

Your test framework had bugs in it, which means that your tests were buggy.  This is the problem with complex tests and complex testing systems.  One way to deal with this is to create unit tests for the complex parts, and then confirm that they behave correctly.

In other words, it's just software, and if it isn't dead simple, it probably needs testing.

Title: How do you test a selenium framework?


问:
Is there a Haskell idiom for trying several functions and stop as soon as one succeeds?
In Haskell, I can use the type a -> Maybe b to model a function that either returns a value of type b, or returns nothing (it fails).

If I have types a1, ..., a(n+1) and functions f1, ..., fn, with fi :: ai -> Maybe a(i+1) for all i, 1 <= i <= n, I can chain the functions by using the >>= operator of the Maybe monad and write:

```<code>f1 x >>= f2 >>= f3 >>=... >>= fn
</code>```

The >>= operator ensures that each function is applied as long as its predecessor has returned a meaningful value. As soon as a function in the chain fails, the whole chain fails (returns Nothing) and further functions in the chain are not evaluated.

I have a somewhat similar pattern in which I want to try several functions on the same input, and return as soon as one function succeeds. If all functions fail (return Nothing), the whole computation should fail. More precisely, I have functions f1, ..., fn :: a -> Maybe b and I define the function

```<code>tryFunctions :: [a -> Maybe b] -> a -> Maybe b
tryFunctions []       _ = Nothing
tryFunctions (f : fs) x = case f x of
                            Nothing    -> tryFunctions fs x
                            r@(Just _) -> r
</code>```

In a sense this is dual to the Maybe monad in that a computation stops at the first success instead of at the first failure.

Of course, I can use the function I have written above but I was wondering if there is a better, well-established and idiomatic way of expressing this pattern in Haskell.

答:
In the spirit of Conal, break it into smaller simpler operations.

In this case, asum from Data.Foldable does the main part.

```<code>tryFunction fs x = asum (map ($ x) fs)
</code>```

Alternatively, a la Jimmy Hoffa's reply you can use the Monoid instance for (->) but then you need a Monoid instance for Maybe and the standard one doesn't do what you want.  You want First from Data.Monoid.

```<code>tryFunction = fmap getFirst . fold . map (fmap First)
</code>```

(Or mconcat for an older, more specialized version of fold.)

Body:
In the spirit of Conal, break it into smaller simpler operations.

In this case, asum from Data.Foldable does the main part.

tryFunction fs x = asum (map ($ x) fs)

Alternatively, a la Jimmy Hoffa's reply you can use the Monoid instance for (->) but then you need a Monoid instance for Maybe and the standard one doesn't do what you want.  You want First from Data.Monoid.

tryFunction = fmap getFirst . fold . map (fmap First)

(Or mconcat for an older, more specialized version of fold.)


问:
Haskell types for functions
I don't understand the answer to this question:

Q: Can Haskell find a type for the function selfapply defined by: selfapply f = f f

A: The function selfapply is not typeable in the simple system of types: we need to associate to f two types which are not compatible: α → α and α.

So I know a -> a means alpha input and alpha return, but why is it a->a and a instead of a->a->a?

Also another question regarding this topic:

Find a polymorphic type for the functions quad, double

```<code>quad x = y*y where y = x*x
double x = x*2
</code>```

How can we determine a polymorphic type for these two functions?

答:
There are a couple of levels to your first question.  As an aside, though, I recommend learning about unification if you are not already familiar with it as it is a key part of understanding type checking and type inference.

To type check selfApply provisionally give f the type a which we will solve for.  (At this point it is just a unification variable, the key difference between Hindley-Milner type checking and type checking for simple types is that we'll generalize (quantify over) any unbound variables at the end.)  Since we are using f as a function we know a = b -> c for new variables b and c.  Since we are applying f to something of type a, namely f itself, we know b = a.  There is no constraint on c, so you are correct to be confused about the provided answer since f isn't required to be a and a -> a and it could indeed be a and a -> a -> a or a and a -> Bool as well.  Of course, as you no doubt understand, the issue is solving the equation a = a -> c.  In attempting to unify these with traditional unification we will fail what is known as the occurs check.  This check is to avoid infinite terms.  Rational tree unification is, however, one way to deal with this issue and leads to equi-recursive types.  Haskell intentionally does not support equi-recursive types, but O'Caml, for example, does with the -rectypes flag.  To validate that c is free we can use an iso-recursive type, namely:

```<code>data X c = X (X c -> c)
selfApply f = f (X f)
</code>```

which will type check, and, in particular, selfApply :: (X c -> c) -> c.

There are two reasons Haskell (and almost all polymorphic languages) do not support equi-recursive types.  First, pragmatically, many type errors show up as infinite types and if equi-recursive types were supported (tacitly) then they'd turn into broken but type correct programs.  More philosophically, outlawing equi-recursive types and similar things was exactly why type systems were originally invented going all the way back to Bertrand Russell.

Title: Haskell types for functions

Body:
There are a couple of levels to your first question.  As an aside, though, I recommend learning about unification if you are not already familiar with it as it is a key part of understanding type checking and type inference.

To type check selfApply provisionally give f the type a which we will solve for.  (At this point it is just a unification variable, the key difference between Hindley-Milner type checking and type checking for simple types is that we'll generalize (quantify over) any unbound variables at the end.)  Since we are using f as a function we know a = b -> c for new variables b and c.  Since we are applying f to something of type a, namely f itself, we know b = a.  There is no constraint on c, so you are correct to be confused about the provided answer since f isn't required to be a and a -> a and it could indeed be a and a -> a -> a or a and a -> Bool as well.  Of course, as you no doubt understand, the issue is solving the equation a = a -> c.  In attempting to unify these with traditional unification we will fail what is known as the occurs check.  This check is to avoid infinite terms.  Rational tree unification is, however, one way to deal with this issue and leads to equi-recursive types.  Haskell intentionally does not support equi-recursive types, but O'Caml, for example, does with the -rectypes flag.  To validate that c is free we can use an iso-recursive type, namely:

data X c = X (X c -> c)
selfApply f = f (X f)

which will type check, and, in particular, selfApply :: (X c -> c) -> c.

There are two reasons Haskell (and almost all polymorphic languages) do not support equi-recursive types.  First, pragmatically, many type errors show up as infinite types and if equi-recursive types were supported (tacitly) then they'd turn into broken but type correct programs.  More philosophically, outlawing equi-recursive types and similar things was exactly why type systems were originally invented going all the way back to Bertrand Russell.


问:
Functional Programming style: How to write functions - explicit currying, implicit currying or lamdas?
So I have been using F# for a while and studying a bit of Haskell on the side and I have realized I could rewrite the exact same function one of three different ways.

Either with implicit currying, explicit currying, or with lambda expressions.

```<code>//lambdas
let add'  =  fun x -> fun y -> x + y

//explicit currying
let add' x  =
   let subFunction y =
      x + y
   subFunction

//implicit currying
let add' x y = x + y
</code>```

All of these have the signature int -> int -> int. All of them do the same thing.

Which one should I use in which case?

答:
The answer to your question is the "implicit currying" option.  However, there are times where you would use the second option.

In Haskell, for performance, you may want to share some work in the partially applied result.  (Note, nothing in the Report guarantees this sharing or precludes the compiler from lifting out the work itself.  In practice, GHC doesn't do these sorts of transformations for good reasons.)

```<code>addC x = let c = large computation x in \y -> x + y + c
</code>```

In Haskell this is semantically equivalent to the following though in practice will have different performance characteristics.

```<code>addC x y = let c = large computation x in x + y + c
</code>```

In F# the difference can be semantically meaningful.

```<code>let foo x = let rx = ref x in fun y -> rx := !rx + 1; !rx + y;;
</code>```

is very different from

```<code>let foo x y = let rx = ref x in rx := !rx + 1; !rx + y;;
</code>```

Body:
The answer to your question is the "implicit currying" option.  However, there are times where you would use the second option.

In Haskell, for performance, you may want to share some work in the partially applied result.  (Note, nothing in the Report guarantees this sharing or precludes the compiler from lifting out the work itself.  In practice, GHC doesn't do these sorts of transformations for good reasons.)

addC x = let c = large computation x in \y -> x + y + c

In Haskell this is semantically equivalent to the following though in practice will have different performance characteristics.

addC x y = let c = large computation x in x + y + c

In F# the difference can be semantically meaningful.

let foo x = let rx = ref x in fun y -> rx := !rx + 1; !rx + y;;

is very different from

let foo x y = let rx = ref x in rx := !rx + 1; !rx + y;;


答:
C is a low-level language, nearly a portable assembler, so its data structures and language constructs are close to the metal (data structures have no hidden costs - except padding, alignment and size constraints imposed by hardware and ABI). So C indeed does not have dynamic typing natively. But if you need it, you could adopt a convention that all your values are aggregates starting with some type information (e.g. some enum ...); use union-s and (for array-like things) flexible array member in struct containing also the size of the array.

(when programming in C, it is your responsibility to define, document, and follow useful conventions - notably pre- and post- conditions and invariants; also C dynamic memory allocation requires expliciting conventions about who should free some heap-mallocated memory zone)

So, to represent values which are boxed integers, or strings, or some kind of Scheme-like symbol, or vectors of values, you'll conceptually use a tagged union (implemented as a union of pointers) -always starting by the type kind-, e.g.:

```<code>enum value_kind_en {V_NONE, V_INT, V_STRING, V_SYMBOL, V_VECTOR};
union value_en { // this union takes a word in memory
   const void* vptr; // generic pointer, e.g. to free it
   enum value_kind_en* vkind; // the value of *vkind decides which member to use
   struct intvalue_st* vint;
   struct strvalue_st* vstr;
   struct symbvalue_st* vsymb;
   struct vectvalue_st* vvect;
};
typedef union value_en value_t;
#define NULL_VALUE  ((value_t){NULL})
struct intvalue_st {
  enum value_kind_en kind; // always V_INT for intvalue_st
  int num;
};
struct strvalue_st {
  enum value_kind_en kind; // always V_STRING for strvalue_st
  const char*str;
};
struct symbvalue_st {
  enum value_kind_en kind; // V_SYMBOL
  struct strvalue_st* symbname;
  value_t symbvalue;
};
struct vectvalue_st {
  enum value_kind_en kind; // V_VECTOR;
  unsigned veclength;
  value_t veccomp[]; // flexible array of veclength components.
};
</code>```

To get the dynamic type of some value

```<code>enum value_kind_en value_type(value_t v) {
  if (v.vptr != NULL) return *(v.vkind);
  else return V_NONE;
}
</code>```

Here is a "dynamic cast" to vectors:

```<code>struct vectvalue_st* dyncast_vector (value_t v) {
   if (value_type(v) == V_VECTOR) return v->vvect;
   else return NULL;
}
</code>```

and a "safe accessor" inside vectors:

```<code>value_t vector_nth(value_t v, unsigned rk) {
   struct vectvalue_st* vecp = dyncast_vector(v);
   if (vecp && rk < vecp->veclength) return vecp->veccomp[rk];
   else return NULL_VALUE;
}
</code>```

You'll typically define most of the short functions above as static inline in some header file.

BTW, if you can use Boehm's garbage collector you are then able to code quite easily in some higher-level (but unsafe) style, and several Scheme interpreters are done that way. A variadic vector constructor could be

```<code>value_t make_vector(unsigned size, ... /*value_t arguments*/) {
   struct vectvalue_st* vec = GC_MALLOC(sizeof(*vec)+size*sizeof(value));
   vec->kind = V_VECTOR;
   va_args args;
   va_start (args, size);
   for (unsigned ix=0; ix<size; ix++)
     vec->veccomp[ix] = va_arg(args,value_t);
   va_end (args);
   return (value_t){vec};
}
</code>```

and if you have three variables

```<code>value_t v1 = somevalue(), v2 = otherval(), v3 = NULL_VALUE;
</code>```

you could build a vector from them using make_vector(3,v1,v2,v3)

If you don't want to use Boehm's garbage collector (or design your own one) you should be very careful about defining destructors and documenting who, how, and when memory should be free-d; see this example. So you could use malloc (but then test against its failure) instead of GC_MALLOC above but you need to carefully define and use some destructor function void destroy_value(value_t)

The strength of C is to be low-level enough to make code like above possible and define your own conventions (particular to your software).

Title: How useful is C's "true" sizing of variables?

Body:
One thing that always intuitively struck me as a positive feature of C (well, actually of its implementations like gcc, clang, ...) is the fact that it does not store any hidden information next to your own variables at runtime. By this I mean that if you for example wanted a variable "x" of the type "uint16_t", you could be sure that "x" will only occupy 2 bytes of space (and won't carry any hidden information like its type etc.). Similarly, if you wanted an array of 100 integers, you could be sure it is as big as 100 integers.

However, the more I am trying to come up with concrete use cases for this feature the more I am wondering if it actually has any practical advantages at all. The only thing I could come up with so far is that it obviously needs less RAM. For limited environments, like AVR chips etc., this is definitely a huge plus, but for everyday desktop / server use cases, it seems to be rather irrelevant. Another possibility I am thinking of is that it might be helpful / crucial for accessing hardware, or maybe mapping memory regions (for example for VGA output and the like) ... ?

My question: Are there any concrete domains that either can't or can only very cumbersomely be implemented without this feature?

P.S. Please tell me if you have a better name for it! ;)

Body:
C is a low-level language, nearly a portable assembler, so its data structures and language constructs are close to the metal (data structures have no hidden costs - except padding, alignment and size constraints imposed by hardware and ABI). So C indeed does not have dynamic typing natively. But if you need it, you could adopt a convention that all your values are aggregates starting with some type information (e.g. some enum ...); use union-s and (for array-like things) flexible array member in struct containing also the size of the array.

(when programming in C, it is your responsibility to define, document, and follow useful conventions - notably pre- and post- conditions and invariants; also C dynamic memory allocation requires expliciting conventions about who should free some heap-mallocated memory zone)

So, to represent values which are boxed integers, or strings, or some kind of Scheme-like symbol, or vectors of values, you'll conceptually use a tagged union (implemented as a union of pointers) -always starting by the type kind-, e.g.:

enum value_kind_en {V_NONE, V_INT, V_STRING, V_SYMBOL, V_VECTOR};
union value_en { // this union takes a word in memory
   const void* vptr; // generic pointer, e.g. to free it
   enum value_kind_en* vkind; // the value of *vkind decides which member to use
   struct intvalue_st* vint;
   struct strvalue_st* vstr;
   struct symbvalue_st* vsymb;
   struct vectvalue_st* vvect;
};
typedef union value_en value_t;
#define NULL_VALUE  ((value_t){NULL})
struct intvalue_st {
  enum value_kind_en kind; // always V_INT for intvalue_st
  int num;
};
struct strvalue_st {
  enum value_kind_en kind; // always V_STRING for strvalue_st
  const char*str;
};
struct symbvalue_st {
  enum value_kind_en kind; // V_SYMBOL
  struct strvalue_st* symbname;
  value_t symbvalue;
};
struct vectvalue_st {
  enum value_kind_en kind; // V_VECTOR;
  unsigned veclength;
  value_t veccomp[]; // flexible array of veclength components.
};

To get the dynamic type of some value

enum value_kind_en value_type(value_t v) {
  if (v.vptr != NULL) return *(v.vkind);
  else return V_NONE;
}

Here is a "dynamic cast" to vectors:

struct vectvalue_st* dyncast_vector (value_t v) {
   if (value_type(v) == V_VECTOR) return v->vvect;
   else return NULL;
}

and a "safe accessor" inside vectors:

value_t vector_nth(value_t v, unsigned rk) {
   struct vectvalue_st* vecp = dyncast_vector(v);
   if (vecp && rk < vecp->veclength) return vecp->veccomp[rk];
   else return NULL_VALUE;
}

You'll typically define most of the short functions above as static inline in some header file.

BTW, if you can use Boehm's garbage collector you are then able to code quite easily in some higher-level (but unsafe) style, and several Scheme interpreters are done that way. A variadic vector constructor could be

value_t make_vector(unsigned size, ... /*value_t arguments*/) {
   struct vectvalue_st* vec = GC_MALLOC(sizeof(*vec)+size*sizeof(value));
   vec->kind = V_VECTOR;
   va_args args;
   va_start (args, size);
   for (unsigned ix=0; ix<size; ix++)
     vec->veccomp[ix] = va_arg(args,value_t);
   va_end (args);
   return (value_t){vec};
}

and if you have three variables

value_t v1 = somevalue(), v2 = otherval(), v3 = NULL_VALUE;

you could build a vector from them using make_vector(3,v1,v2,v3)

If you don't want to use Boehm's garbage collector (or design your own one) you should be very careful about defining destructors and documenting who, how, and when memory should be free-d; see this example. So you could use malloc (but then test against its failure) instead of GC_MALLOC above but you need to carefully define and use some destructor function void destroy_value(value_t)

The strength of C is to be low-level enough to make code like above possible and define your own conventions (particular to your software).


问:
Command pattern and open-closed-principle
Does the command pattern uses OCP ?

In a command patter the invoker is only extensible by actually extending the class. If we want to add custom methods to it, we can make our own sub-class or we could modify the base class's constructor, which violates the open/closed principle.

Which leads me to the question, is the command pattern using OCP or not

答:
If we encounter a case when our design, that uses some specific pattern, cannot accommodate a new requirement without some modifications, it won't mean that the pattern (doesn't matter which one) is bad and violates some good design principles.

It will mean only that our design is not prepared to gracefully handle such cases.

Is it a failure of our upfront design?

In some cases yes. But more than often it is a sign of either of the:

Changing requirements.

Insufficient domain knowledge.

You may and should consider your design carefully, but no matter how adaptive your system is, once upon a time either requirements will change or some piece of obscure domain knowledge will force you to change even the most well-designed system.

Is it bad that we have to modify our system in such cases?

Probably not. You can't design system that can be extended in any possible way without compromising other good design principles. Because such systems will usually sacrifice performance and(or) ease of understanding.

It is a guilty fun to read about similar overly adaptive systems on thedailywtf, but you don't want to end up maintaining one.

Won't it turn the system into a Big Ball of Mud?

If such changes will be made without any considerations about bigger design, then probably yes. But if you apply such changes with proper commitment to reconsidering and, possibly, refactoring them during the consolidation phase then you will be able to hold the entropy in check.

So, does the Command pattern violate the Open-Closed principle?

No. In most cases it is the system's requirements that make specific usage of this pattern not as open-closed as we'd liked it to be.


答:
The one-liner definition of OCP is very nice, although it tends to mislead.

Quoting the original Bob Martin's article on OCP:

It should be clear that no significant program can be 100% closed. ... In general, no matter how “closed” a module is, there
  will always be some kind of change against which it is not closed.

(I really recommend you reading the whole paper and also Jon Skeet's critique)

So basically, OCP is more about finding the right design balance to be able to add a new functionality while breaking the least stuff possible, e.g. be able to extend and not have to modify the codebase thoroughly.

Therefore, it's more about upholding existing interfaces and contracts while modifying existing code.

Whether a command pattern breaks OCP is based more on where and how it is used than the pattern itself. And since you provided no context of usage, your question is not really answerable.

Title: Command pattern and open-closed-principle

Body:
Does the command pattern uses OCP ?

In a command patter the invoker is only extensible by actually extending the class. If we want to add custom methods to it, we can make our own sub-class or we could modify the base class's constructor, which violates the open/closed principle.

Which leads me to the question, is the command pattern using OCP or not


答:
Openness towards change is a strategic decision. That means it is up to designer to choose against which changes the code will be open and against which it will not. Also, quite often, making design open against one change will make it harder to make it open against another.

Command pattern makes the the design open against change of adding new behavior with each behavior being usable in one context (eg. common setup or teardown of behaviors). It is not open against changing existing commands (unless decorator can be applied) and against changes to how the command is setup.

If you find you want make design open against those changes, you should either extend the design or scrap the design and start again with the new requirements.


问:
Using the Apache License 2.0 By Reference Only
I want to license my software with the Apache License 2.0. The software is only a single file of source code. I do not want to include the entire license verbatim in the code. The license appendix describes how I may apply the license to my work by reference. This is done by including text in my software, referring to the license, which I am willing to do.

Recipients of my software then clearly will be subject to the terms of the license, one of which is a redistribution restriction (section 4(a)). That restriction requires that recipients who want to redistribute the work "must give any other recipients of the Work or Derivative Works a copy of this License".

Does this mean that recipients who want to redistribute the work must include 2 files, instead of merely 1 - the single file of source code, and a copy of the license?

答:
Yes, that is what it means.

However, it is recommended that you already include that second file with a copy of the license, just to avoid that a (potential) user of your software needs to go to a different site (which might be down or unreachable from their location) to read what their rights and obligations are.


答:
On the very page of the Apache 2.0 license, it is explained how to include a boilerplate notice into the comment section of your work.
This notice is sufficient to inform any users of their rights and obligations in regards to your work.</p>

Title: Using the Apache License 2.0 By Reference Only

Body:
I want to license my software with the Apache License 2.0. The software is only a single file of source code. I do not want to include the entire license verbatim in the code. The license appendix describes how I may apply the license to my work by reference. This is done by including text in my software, referring to the license, which I am willing to do.

Recipients of my software then clearly will be subject to the terms of the license, one of which is a redistribution restriction (section 4(a)). That restriction requires that recipients who want to redistribute the work "must give any other recipients of the Work or Derivative Works a copy of this License".

Does this mean that recipients who want to redistribute the work must include 2 files, instead of merely 1 - the single file of source code, and a copy of the license?


问:
Database Design - lots of small tables or fewer, bigger tables?
So I'm designing a database for a project which is going to enable beauty businesses to create a profile, clients to create a profile and for the client's to be able to book appointments and for the businesses to manage appointments and their clients.

I have the following tables and fields so far(I've kept is as simple as possible on here but there is more to the tables on paper):

```<code>BUSINESS_TABLE
id (PK)
name
address
contact
about
website

TREATMENT_TABLE
id (PK)
name
description
duration
price

CLIENT_TABLE
id (PK)
name
address
contact
about
current_medical
medical_history
notes

EMPLOYEE_TABLE
id (PK)
name
address
business_id (FK)
business_name (JOIN)
availability_days
availability_hours

APPOINTMENT_TABLE
id (PK)
client_id (FK)
client_name (JOIN)
business_id (FK)
business_name (JOIN)
employee_id (FK)
employee_name (JOIN)
treatment_id (FK)
treatment_name (JOIN)
treatment_duration (JOIN)
treatment_price (JOIN)
appointment_day
appointment_time
</code>```

So I think I've normalised it correctly:

Business can have many clients, appointments, treatments and employees
Clients can have many appointments
Treatments don't have anything
Employees are not linked back to business to keep things simple for now
Appointments take treatments, businesses, employees and clients

So APPOINTMENT_TABLE is the linking table and all the rest feed into it.

Apart from checking to see if my logic is right, I was also asking whether I should split up the CLIENT_TABLE into more, smaller tables as there are 11 fields under the current_medical category and 20 fields in the medical_history category and both of these can be added to at any time. I think that it'll be worth putting these two in separate tables and JOINing them to the CLIENT_TABLE for organisation and being able to amend them more easily (though a little more complex in programming).

I would be grateful to hear any opinions.

Thanks,

Michelle

答: You shouldn't split a normalized table just because it have "many" fields. It will not make anything easier.</p>


问:
How to deal with Classes having the same name (different packages)
Me and my R&D team maintain a large codebase. We've divided our business logic into multiple packages. some of which have classes with identical names.

As you can guess, the names conflict when both classes are referenced in the same Java file.

For example:

```<code>com.myapp.model (package)
 - Device (class)
 - ...

com.myapp.data (package)
 - Device (class)
 - ...
</code>```

We had a debate on what's the best practice to treat these cases and the following options came up:

1st Option

Renaming the class, adding a prefix

```<code>ModelDevice
DataDevice
</code>```

2nd Option

Using the full package+class name when both are referenced

```<code>com.myapp.model.Device
com.myapp.data.Device
</code>```

What's more correct in terms of code management and scalability?

we are currently mixing both approaches and starting to have inconsistency

答: Use the package name. This type of problem is precisely why Java uses the package naming convention that it does. It prevents these sorts of problems, whether it's two teams in the same company or two teams on opposite sides of the earth.</p>

ContentLicense: CC BY-SA 4.0


问:
Best practice for getting last record inserted in DB
Me and a couple of colleagues are having a discussion regarding the following case:

In an OrderStatus table we're keeping track of all the statuses an order goes through in time, including "Pending", "Available", "Returned", etc. There's a timestamp field in the table to keep track of when each status was added. However, there are two statuses that may be added exactly at the same time, one after the other, in which case both may have exactly the same timestamp (including milliseconds). In another part of the code, we need to check which is the last status an order was set to, and since we're ordering by the timestamp we can easily get the wrong record from the database.

The table has an IDENTITY(1,1) primary key, and my colleagues think we should order using that column, since that will always necessarily give you the latest record added to the table.

I feel like an IDENTITY column should be voided of any meaning and thus should not be used for any sorting, and would rather do a Thread.Sleep(1) to make sure the timestamps are different and we can keep sorting using that field.

What do you think is the best practice in this case?

答:
Your colleague is right. Order by the primary key. The primary key is not devoid of meaning. It identifies each row in the table. It is numeric, which implies the order in which records were created.

It doesn't fit perfectly into the terminology of your business domain, but don't overlook the simple and obvious solution for ideological reasons, especially when this solution requires little more than a sort clause in a SQL query.


答:
The names of your tables should be BUSINESSES, TREATMENTS, CLIENTS, EMPLOYEES,
APPOINTMENTS.  Nobody appends "_TABLE" to their table names, just as nobody appends "_Word_Document" to their word document names.

Also, we usually do not include joined fields in table designs.  The fact that these fields are available is evident by the presence of the foreign key.

Other than that, your design looks fine.  I would recommend against splitting the fields of any table.  If you have a performance issue, look into partitioning.  If you have any other table editing issue, then the problem might be in how you plan on handling it, (which makes you think that the table should perhaps be split,) and not in the structure of the table itself.

Title: Database Design - lots of small tables or fewer, bigger tables?

Body:
So I'm designing a database for a project which is going to enable beauty businesses to create a profile, clients to create a profile and for the client's to be able to book appointments and for the businesses to manage appointments and their clients.

I have the following tables and fields so far(I've kept is as simple as possible on here but there is more to the tables on paper):

```<code>BUSINESS_TABLE
id (PK)
name
address
contact
about
website

TREATMENT_TABLE
id (PK)
name
description
duration
price

CLIENT_TABLE
id (PK)
name
address
contact
about
current_medical
medical_history
notes

EMPLOYEE_TABLE
id (PK)
name
address
business_id (FK)
business_name (JOIN)
availability_days
availability_hours

APPOINTMENT_TABLE
id (PK)
client_id (FK)
client_name (JOIN)
business_id (FK)
business_name (JOIN)
employee_id (FK)
employee_name (JOIN)
treatment_id (FK)
treatment_name (JOIN)
treatment_duration (JOIN)
treatment_price (JOIN)
appointment_day
appointment_time
</code>```

So I think I've normalised it correctly:

Business can have many clients, appointments, treatments and employees
Clients can have many appointments
Treatments don't have anything
Employees are not linked back to business to keep things simple for now
Appointments take treatments, businesses, employees and clients

So APPOINTMENT_TABLE is the linking table and all the rest feed into it.

Apart from checking to see if my logic is right, I was also asking whether I should split up the CLIENT_TABLE into more, smaller tables as there are 11 fields under the current_medical category and 20 fields in the medical_history category and both of these can be added to at any time. I think that it'll be worth putting these two in separate tables and JOINing them to the CLIENT_TABLE for organisation and being able to amend them more easily (though a little more complex in programming).

I would be grateful to hear any opinions.

Thanks,

Michelle


问:
What does mapping mean in programming?
I often hear things like:

Mapping the classes

Mapping the objects from the database

Mapping the objects

Mapping the elements of a list

A mapper

What does a mapper and the act of mapping something actually mean?

答:
Generally, "mapping" is some association of some values to other values. It tends to imply a manual sort of process. It tends to imply a fixed association. Consider ASCII values:

```<code>'a' -> 97
'b' -> 98
'c' -> 99
...
</code>```

The entire set of associations is called a mapping (noun). Having the characters and the numbers and making the associations is also called a mapping (verb). It differs from a function, as a function takes some input and produces the output based on some calculation. Mappings generally do not do a calculation, but instead some sort of look-up.

Title: What does mapping mean in programming?

Body:
Generally, "mapping" is some association of some values to other values. It tends to imply a manual sort of process. It tends to imply a fixed association. Consider ASCII values:

'a' -> 97
'b' -> 98
'c' -> 99
...

The entire set of associations is called a mapping (noun). Having the characters and the numbers and making the associations is also called a mapping (verb). It differs from a function, as a function takes some input and produces the output based on some calculation. Mappings generally do not do a calculation, but instead some sort of look-up.


答:
It's a mathematical concept.

www.thefreedictionary.com

```<code>2. Mathematics The correspondence of elements in one set
to elements in the same set or another set.
</code>```

It's to establish a correspondence between two distinct data models.

For example, you can say thay the class User is a representation of a row of the database table USER, that would be object-relational-mapping.

Or you can create a key-value pair list which is saying that a given element of one list corresponds to one element of the other list.

I guess your native tongue is spanish given your username, mapping or "to map" could be translated as emparejar.

Title: What does mapping mean in programming?

Body:
I often hear things like:

Mapping the classes

Mapping the objects from the database

Mapping the objects

Mapping the elements of a list

A mapper

What does a mapper and the act of mapping something actually mean?

Body:
It's a mathematical concept.

www.thefreedictionary.com

2. Mathematics The correspondence of elements in one set
to elements in the same set or another set.

It's to establish a correspondence between two distinct data models.

For example, you can say thay the class User is a representation of a row of the database table USER, that would be object-relational-mapping.

Or you can create a key-value pair list which is saying that a given element of one list corresponds to one element of the other list.

I guess your native tongue is spanish given your username, mapping or "to map" could be translated as emparejar.


答:
The programming uses of the verb "map" and the noun "mapper" are largely unrelated to their common uses in English, so this is a very understandable question.

The programming use is also very broad, so let's start with the most concrete and well-defined meaning of "map". Namely, the higher-order map function present in most functional programming languages. Here's a trivial example of it in Javascript:

```<code>var numbers = [1, 2, 3, 4];
var timesTwo = function(n) {
    return n * 2;
}
numbers.map(timesTwo); // [2, 4, 6, 8]
</code>```

The map function requires an array and another function. It returns a new array which is the result of applying that function to all elements of the original array.

All other uses of the term can, at least in my experience, be considered analogous to this specific one. In the most general sense, "mapping" in programming means taking several things and then somehow associating each of them with another thing.

A typical but imprecise usage in my day-to-day work would be "mapping UI events to handler functions". For instance, when the user clicks button 1, I want handleButton1Click to get called, and when the user hovers over an image, I want handleImageHover to get called.

One of the most high-level uses of this term is ORM (object-relational mapping), which means mapping rows in a relational database to objects in an OOP language, so that you can manipulate "normal" objects in your code without having to directly write SQL or worry about the structure of the database.

Title: What does mapping mean in programming?

Body:
The programming uses of the verb "map" and the noun "mapper" are largely unrelated to their common uses in English, so this is a very understandable question.

The programming use is also very broad, so let's start with the most concrete and well-defined meaning of "map". Namely, the higher-order map function present in most functional programming languages. Here's a trivial example of it in Javascript:

var numbers = [1, 2, 3, 4];
var timesTwo = function(n) {
    return n * 2;
}
numbers.map(timesTwo); // [2, 4, 6, 8]

The map function requires an array and another function. It returns a new array which is the result of applying that function to all elements of the original array.

All other uses of the term can, at least in my experience, be considered analogous to this specific one. In the most general sense, "mapping" in programming means taking several things and then somehow associating each of them with another thing.

A typical but imprecise usage in my day-to-day work would be "mapping UI events to handler functions". For instance, when the user clicks button 1, I want handleButton1Click to get called, and when the user hovers over an image, I want handleImageHover to get called.

One of the most high-level uses of this term is ORM (object-relational mapping), which means mapping rows in a relational database to objects in an OOP language, so that you can manipulate "normal" objects in your code without having to directly write SQL or worry about the structure of the database.


问:
Using prototype/non-Spring managed beans in Spring Web application
I have been working on few web applications/REST web services recently (Spring IoC/MVC/Data JPA etc) and they usually follow the same pattern: Controller classes --> Service classes (which have number of "utility"/business logic classes autowired) --> Spring Data Repositories.

Pretty much all of them classes above are Spring singletons, which sometimes I feel like it makes the code and some functions within a class dirtier (for example because I cant have a state in a class, I need to pass quite a lot parameters between methods, and I dont really like having more than 1-2 parameters, although I know sometimes its necessary).

I was wondering how is this problem overcome in the big (e.g. enterprise) kind of application.

Is it a common practice to use non-Spring managed classes in the Spring application? If so, how do you pass dependencies into it (the ones that would normally be autowired)? If I use constructor injection for example, then I need to autowire all necessary dependencies into the class that creates the object and I wanted to avoid that. Also I dont really want to be messing with load time weaving etc. to autowire beans into non-Spring objects

Is using prototype scoped beans a good solution? The only thing is that I need to use AOP's scoped proxies (or method injection etc) to make sure that I get a new instance for any bean thats autowired into singleton in the first place. Is that a "clean" and reliable option - i.e. is it certain that there will be no concurrency type of issues and can I still autowire any singletons into those classes with no issues?

If anyone that worked on a large system, that actually managed to keep the structure not "bloated" and clean have any recommendations? Maybe there are some patterns I am not aware and could use?

Any help appreciated.

答:
I have been working on Spring projects of various size, fromtiny  microservices (sometimes less than 100 lines of production code) till big monoliths (with 20+ full time developers working on single codebase).

First of all, my experience is that monoliths tend to be often over-complicated and full of accumulated accidental complexity. Therefore if you feel that your team is experiencing inefficiency caused by bloated codebase, you should consider splitting it into more autonomous and separately manageable components. It doesn't matter if you are using Spring.

Secondly, maybe you encountered Functional Programming movement that is taking over mainly alpha geek community. One of the fundamental ideas of Functional Programming is strict separation of code and data. Actually functional programmers believe strongly that it is terrible idea to combine data (state) with code into objects as it is done often in object oriented programming.

I personally also believe that encapsulating state into bunch of objects and defining logic on these objects to mutate this state will create huge mess in monolithic applications. No matter how great developers you have on the project, they will create codebase that is hard to maintain, as state mutations issues are often very tricky to reproduce and discover.

In that regard, Spring default singleton scope actually makes codebase much easier, because you should always strive for not defining any state on singleton beans. Think about them as a code only, where all of them are strictly stateless.

State in your application represents scalability problem, because if you have stateful application you can't have various instances of it. So state should always be handled carefully in caches or storages dedicated to storing state (e.g. distributed caches or data grids or databases).

Now to the first bullet point, do not try to inject non-Spring beans into Spring singleton beans. I work with Spring 5+ years and I can remember only one case where I used Prototype scope. Just create your DTOs via constructor and do not mix them with Spring context. It is wise idea to keep these DTOs as dumm as possible. That means use create only getters/setters/toString and hashcode/equals for them if needed. I highly recommend using Lombok project for generating these boilerplate methods, so that your DTOs are very readable.

To the point about a lot of parameters passing around. Just group these parameters into higher level DTO. E.g. if you are passing around parameters: customerName, customerId, customerCreditCardNumber, just create DTO Customer and pass that around. Easy enough. If don't want to pass around anything, just use Request scope to bind state to the current request. All the beans can autowire this Request scope bean and mutate its state. But this should be very rare and exceptional case as it may hide tricky behavior often. It's equivalent of global variable for request. Bad idea generally.

To the second bullet point. I believe it was covered already with my other points.

I know that these approaches are significantly deviating from what we've learnt on the college when OOP was the preferred approach. But industry slowly starting to realize that it wasn't right approach for writing complex web applications. I highly recommend looking into functional programming principles as they seem to be the future.


问:
Why are constructors not inherited?
I am confused as to what the problems could be if a constructor was inherited from a base class. Cpp Primer Plus says,

Constructors are different from other class methods in that they
  create new objects, whereas other methods are invoked by existing
  objects. This is one reason constructors aren’t inherited. Inheritance
  means a derived object can use a base-class method, but, in the case
  of constructors, the object doesn’t exist until after the
  constructor has done its work.

I understand  the constructor is called before object construction is completed.

How can it lead to problems if a child class inherits (By inheriting I mean the child class is able to override the parent class method etc. Not just accessing the parent class method) the parent constructor?

I understand there is no necessity of explicitly calling a constructor from within a code[not that I am aware of as yet.] except while creating objects. Even then you can do so using some mechanism to invoke the parent constuctor [ In cpp, using :: or using member initialiser list, In java using super]. In Java there is an enforcement to call it in the 1st line, I understand that is to ensure the parent object is created first and then the child object construction proceeds.

It can overrride it. But, I can't come up with situations where this can pose a problem. If the child does inherit the parent constructor what can go wrong?

So is this just to keep away from inheriting unecessary functions. Or is there more to it?

答:
Every class needs a constructor, even the defaults ones.

C++ will create default constructors for you except if you create a specialized constructor.

In case that your base class uses a specialized constructor, you will need to write the specialized constructor on the derived class even if both are the same and chain them back.

C++11 allow you to avoid code duplication on constructors using using:

```<code>Class A : public B {
using B:B;
....
</code>```

A set of inheriting constructors is composed of

All non-template constructors of the base class (after omitting ellipsis parameters, if any) (since C++14)

For each constructor with default arguments or the ellipsis parameter, all constructor signatures that are formed by dropping the ellipsis and omitting default arguments from the ends of argument lists one by one

All constructor templates of the base class (after omitting ellipsis parameters, if any) (since C++14)

For each constructor template with default arguments or the ellipsis, all constructor signatures that are formed by dropping the ellipsis and omitting default arguments from the ends of argument lists one by one

All inherited constructors that aren't the default constructor or the copy/move constructor and whose signatures do not match user-defined constructors in the derived class, are implicitly declared in the derived class. The default parameters are not inherited

Title: Why are constructors not inherited?

Body:
Every class needs a constructor, even the defaults ones.

C++ will create default constructors for you except if you create a specialized constructor.

In case that your base class uses a specialized constructor, you will need to write the specialized constructor on the derived class even if both are the same and chain them back.

C++11 allow you to avoid code duplication on constructors using using:

Class A : public B {
using B:B;
....

A set of inheriting constructors is composed of

All non-template constructors of the base class (after omitting ellipsis parameters, if any) (since C++14)

For each constructor with default arguments or the ellipsis parameter, all constructor signatures that are formed by dropping the ellipsis and omitting default arguments from the ends of argument lists one by one

All constructor templates of the base class (after omitting ellipsis parameters, if any) (since C++14)

For each constructor template with default arguments or the ellipsis, all constructor signatures that are formed by dropping the ellipsis and omitting default arguments from the ends of argument lists one by one

All inherited constructors that aren't the default constructor or the copy/move constructor and whose signatures do not match user-defined constructors in the derived class, are implicitly declared in the derived class. The default parameters are not inherited


问:
What are important things to remember when reengineering a legacy application?
About to embark on the initial phases of a project to rewrite a legacy application from the ground up (existing business rules will change somewhat, and be extended to incorporate a large number of new requirements that the existing infrastructure cannot handle). I am looking for items that are important to remember when working to reengineer an existing application.</p>

答: Write a suite of unit tests for the existing functionality first.  When you do your rewrite, you can use this unit test suite to verify that your existing business rules still work in the new application.

ContentLicense: CC BY-SA 2.5


问:
Why do python generators and functions share the "def" keyword?
Consider the following:

```<code>def some_function():
    return 1

def some_generator():
    yield 1
</code>```

In the code above, some_function is a function, while some_generator is a generator. They look quite similar.

The problem that I have when reading code is that I need to scan through every line in a "function" looking for the yield keyword before I can determine whether it is actually a function or a generator!

It just seems to me that using a different keyword for generators would make more sense, e.g.:

```<code>gen some_generator():
    yield 1
</code>```

What are the merits of using the def keyword for both generators and functions? Why has a new keyword is not been introduced to separate functions and generators?

答:
Adding new keywords risks breaking existing programs.  Language designers generally try to avoid adding new keywords, especially for language features added after the language has already gained some popularity.  Every keyword they add is an identifier that programs aren't allowed to use for other purposes, so adding a keyword could potentially break existing programs.  Language designers have to weigh the benefits of a new keyword against the costs.

I doubt that defining a separate keyword for generators would have much benefit. To understand whether a symbol corresponds to the name of a function or to the name of a generator is something that matters to callers, and callers shouldn't have to (and sometimes can't) look at what keyword was used to implement it.  That's the responsibility of better naming conventions and documentation.


问:
What is early and late binding?
I keep hearing about early and late binding, but I do not understand what they are. I found the following explanation which I do not understand:

Early binding refers to assignment of values to variables during design time whereas late binding refers to assignment of values to variables during run time.

Could someone please define the two types of binding and compare them?

答:
Perhaps the most common example of late binding is resolving Internet URLs.  It supports dynamic systems and large systems without trying to link and bind every site in the world before you can reach any, but on the other hand it does incur some overhead (DNS lookup, much less IP routing) at runtime.

By that light, most varieties of binding in language environments is more or less early, at compile time or link time.

Each kind has costs and benefits.

Title: What is early and late binding?


问:
What is the difference between a 3rd party lib and a plugin
What is the difference between a 3rd party lib and a plugin?

How do I choose what should be pushed to these repos?

```<code>plugins-release-local = Your and 3rd party plugins (releases)
plugins-snapshot-local =  Your and 3rd party plugins (snapshots)

ext-release-local = Manually deployed 3rd party libs (releases)
ext-snapshot-local = Manually deployed 3rd party libs (snapshots)
</code>```

答:
A "plugin" is a piece of code that's meant to be integrated with a specific application, and cannot be reused elsewhere. A "library" is some code that's meant to be used by other programmers for a specific purpose, but could be useful for many different applications.

For example, AdBlock for Google Chrome is a plugin. It needs to be hooked up to the full Google Chrome application before it can do anything remotely useful. Immutable.js is a library. It can be used by pretty much any (Javascript) application as long as it has a use case for immutable data structures.

Normally, removing a plugin from an application will only remove one feature, while removing a library the application depends on will probably break it completely. Normally, plugins are created after the application is developed, while the libraries the application uses already existed. Normally, which libraries an application uses is purely up to the application developers, while the plugins that get used are up to the end users.

I know very little about Java or Maven, but this is what the terms normally mean, and I'm not aware of any reason the Java world would have redefined them.


问:
How can I sell DRY?
Where I work we have around 10 VS projects in a solution which are identical in functionality (with some different different rules in a few methods) and share many exact methods. They share the same namespace and the classes are called with if else's individually.

I believe it would be better and more succinct to have an interface and an abstract class with protected methods which are common among all the children.

The methods which take one of these classes can then take an Interface rather than have 10 different methods which take one and run the same method on each class.

The public methods all have the same signature and return the same thing.

Future implementations of the class will have a clear guideline on how to implement it (other than copy pasting and editing a previous version) and it is more maintainable. The reason I am considering this is because I am adding an extra version and unhappy with the idea of copying and pasting a lot of mess and changing all the bits I need to change (just in 2-3 long methods of ~20 methods)

I am having difficulty expressing my reasons to why I should be allowed to make these changes (would probably not take more than a day and changes no logic so minimal testing is required). I know intuitively it is better but that is not good enough!

How do I explain to the lead dev when DRY is a good thing? Or is he right that we should just keep copy and pasting things because we "inherited the code this way"?

答:
It sounds like you're using inheritance to share behavior between classes. You should favor 'object composition' over 'class inheritance'. This is not cut and dry and context matters, but you should give thought to whether you need your abstract class.

As far as the interface goes, it sounds like a good idea, branching often is a sign that code could be better designed. I would however do this as Boy Scout refactoring. Basically, leave the code tidier than you found it, but keep refactoring within the context of the task that led you to that code. Next time you visit that branching method maybe create an interface, do some trivial renaming and send it to your colleagues for code review. Your change and it's justifications will be a lot more concrete at that point.

Don't try and fix the world at once and don't try to set the standard for "Future implementations" all at once. Improvement should be be in small bites, yet continuous.

Title: How can I sell DRY?


问:
How does breaking up a big method into smaller methods improve unit testability when the methods are all private?
I'm presently reading Building Maintainable Software by Joost Visser and some of the maintenance guidelines they recommend include: A) each unit/method should be short (less than 15 lines per method) and B) methods should have a low cyclomatic complexity. It suggests that both these guideline helps with testing.

The example below is from the book explaining how they would refactor a complex method to reduce the per method cyclomatic complexity.

Before:

```<code>public static int calculateDepth(BinaryTreeNode<Integer> t, int n) {
    int depth = 0;
    if (t.getValue() == n) {
        return depth;
    } else {
        if (n < t.getValue()) {
            BinaryTreeNode<Integer> left = t.getLeft();
            if (left == null) {
                throw new TreeException("Value not found in tree!");
            } else {
                return 1 + calculateDepth(left, n);
            }
        } else {
             BinaryTreeNode<Integer> right = t.getRight();
             if (right == null) {
                throw new TreeException("Value not found in tree!");
             } else {
                return 1 + calculateDepth(right, n);
             }
        }
    }
}
</code>```

After:

```<code>public static int calculateDepth(BinaryTreeNode<Integer> t, int n) {
     int depth = 0;
     if (t.getValue() == n)
        return depth;
     else
        return traverseByValue(t, n);
}
private static int traverseByValue(BinaryTreeNode<Integer> t, int n) {
     BinaryTreeNode<Integer> childNode = getChildNode(t, n);
     if (childNode == null) {
        throw new TreeException("Value not found in tree!");
     } else {
        return 1 + calculateDepth(childNode, n);
     }
}
private static BinaryTreeNode<Integer> getChildNode(
     BinaryTreeNode<Integer> t, int n) {
     if (n < t.getValue()) {
        return t.getLeft();
     } else {
        return t.getRight();
     }
}
</code>```

In their justification they state (emphasis mine):

Argument:

“Replacing one method with McCabe 15 by three methods with McCabe 5
  each means that overall McCabe is still 15 (and therefore, there are
  15 control ow branches overall). So nothing is gained.”

Counter Argument:

Of course, you will not decrease the overall McCabe complexity of a system by
  refactoring a method into several new methods. But from a
  maintainability perspective, there is an advantage to doing so: it
  will become easier to test and understand the code that was written.
  So, as we already mentioned, newly written unit tests allow you to
  more easily identify the root cause of your failing tests.

Question: How does it become easier to test?

According to the answers to this question, this question, this question, this question and this blog we should not be testing private methods directly. Which means we need to test them via the public methods that use them. So going back to the example in the book, if we are testing the private methods via the public method, then how does the unit tests functionality improve, or change at all for that matter?

答:
After having written lots of test, I am strongly in favour of splitting up large methods, and of testing private methods. Splitting up functionality into smaller steps has two great advantages:

By introducing a name for an operation, the code becomes more self-documenting.

By using smaller methods, the code is simpler and thus more likely correct. E.g. you can immediately understand getChildNode().

While the overall program cyclomatic complexity isn't reduced, these two advantages outweigh the bit of extra code in my book. There is a third advantage: the code becomes much easier to test, assuming we can get around the private access modifier.

People who advise against testing private implementation details make a good point: the test should show that the implementation adheres to it's public interface, but this can only be done by black-box tests of the public methods. Such tests don't require that you get 100% coverage, but missing coverage is an indication of dead code that's not required by the specification. Since TDD tests should define externally observable behaviour, such tests fall into this category.

But you can also use a different approach to testing: showing that an existing implementation is likely correct, and works as the programmer expected. Since we already have the code, we can design our tests to maximize coverage. We can use boundary values to meticulously exercise the behaviour of the program. In other words, we can write white-box tests that know about implementation details of the system under test. These tests are highly coupled to the implementation, but that is OK as long as you also have more general black-box tests.

As a result, I prefer a few black-box tests that walk through the “happy path” and basic guarantees of the interface. But it is way to cumbersome to exercise all possibilities: with each input parameter or state variable in the function, the test space increases exponentially! A function f(bool) might take two tests, a function f(bool, bool) 2²=4, and f(bool, bool, bool, bool) already 24=16. This is untenable. But by splitting a large function into smaller functions, I only have to show that each smaller function works as expected, and that the functions work together correctly (I call this testing by induction). My workload now adds, instead of multiplying – a great improvement if you want to be thorough!

In your concrete example, either possibility is suboptimal because in the first try there's loads of code duplication requiring duplicate testing, and in the second try there are interdependencies between the functions that cannot be mocked away. Only getChildNode() is easy to test, but this function is incorrect if n is equal to t.getValue(), which will never happen if that function is only ever called by traverseByValue(). An easy to test alternative would be:

```<code>public static int calculateDepth(BinaryTreeNode<Integer> t, int n) {
    if (t == null) {
        throw new TreeException("Value not found in tree!");
    }

    if (t.getValue() == n) {
        return 0;
    }

    BinaryTreeNode<Integer> child = null;
    if (n < t.getValue()) {
        child = t.getLeft();
    } else {
        child = t.getRight();
    }

    return 1 + calculateDepth(child, n);
}
</code>```

This specific case doesn't even use any helper functions, because it's simple enough to do without – there are only 4 paths through this code. Your previous implementation hid this by nesting conditionals when the other branch had already been terminated by a throw or return, and by unnecessary code duplication.

However, testing a recursion or loop can be difficult. While we could create a fairly complex tree and check for the correct result, we would like a way to check the loop invariant. In a language with higher-order functions, this might be:

```<code>public static int calculateDepth(
        BinaryTreeNode<Integer> t,
        int n)
{
    return calculateDepthLoop(t, n, calculateDepthLoop);
}

type Recurser = int(BinaryTreeNode<Integer>, int, Recurser);

private static int calculateDepthLoop(
         BinaryTreeNode<Integer> t,
         int n,
         Recurser recurse)
{
    if (t == null) {
        throw new TreeException("Value not found in tree!");
    }

    if (t.getValue() == n) {
        return 0;
    }

    BinaryTreeNode<Integer> child = null;
    if (n < t.getValue()) {
        child = t.getLeft();
    } else {
        child = t.getRight();
    }

    return 1 + recurse(child, n, recurse);
}
</code>```

Now we could run a test plan like:

calculateDepthLoop(null, ANY, ANY) throws.

calculateDepthLoop(Tree(x, ANY, ANY), x, ANY) is0`.

calculateDepthLoop(Tree(x, left, ANY), y, callback) for y < x invokes result = callback(left, y, callback) and returns the result + 1.

calculateDepthLoop(Tree(x, ANY, right), y, callback) for x < y invokes result = callback(right, y, callback) and returns the result + 1.

with only 4 tests (one for each path) we can be sure that calculateDepthLoop() works as expected. We might want a couple more just to be sure that everything works for all valid values of x and y. Now we only need another test to check that everything integrates as it should, this can be done with a black-box test of calculateDepth(), which I'd do by creating a moderately complex tree requiring the function to recurse both left and right and return some value.

Body:
After having written lots of test, I am strongly in favour of splitting up large methods, and of testing private methods. Splitting up functionality into smaller steps has two great advantages:

By introducing a name for an operation, the code becomes more self-documenting.

By using smaller methods, the code is simpler and thus more likely correct. E.g. you can immediately understand getChildNode().

While the overall program cyclomatic complexity isn't reduced, these two advantages outweigh the bit of extra code in my book. There is a third advantage: the code becomes much easier to test, assuming we can get around the private access modifier.

People who advise against testing private implementation details make a good point: the test should show that the implementation adheres to it's public interface, but this can only be done by black-box tests of the public methods. Such tests don't require that you get 100% coverage, but missing coverage is an indication of dead code that's not required by the specification. Since TDD tests should define externally observable behaviour, such tests fall into this category.

But you can also use a different approach to testing: showing that an existing implementation is likely correct, and works as the programmer expected. Since we already have the code, we can design our tests to maximize coverage. We can use boundary values to meticulously exercise the behaviour of the program. In other words, we can write white-box tests that know about implementation details of the system under test. These tests are highly coupled to the implementation, but that is OK as long as you also have more general black-box tests.

As a result, I prefer a few black-box tests that walk through the “happy path” and basic guarantees of the interface. But it is way to cumbersome to exercise all possibilities: with each input parameter or state variable in the function, the test space increases exponentially! A function f(bool) might take two tests, a function f(bool, bool) 2²=4, and f(bool, bool, bool, bool) already 24=16. This is untenable. But by splitting a large function into smaller functions, I only have to show that each smaller function works as expected, and that the functions work together correctly (I call this testing by induction). My workload now adds, instead of multiplying – a great improvement if you want to be thorough!

In your concrete example, either possibility is suboptimal because in the first try there's loads of code duplication requiring duplicate testing, and in the second try there are interdependencies between the functions that cannot be mocked away. Only getChildNode() is easy to test, but this function is incorrect if n is equal to t.getValue(), which will never happen if that function is only ever called by traverseByValue(). An easy to test alternative would be:

public static int calculateDepth(BinaryTreeNode<Integer> t, int n) {
    if (t == null) {
        throw new TreeException("Value not found in tree!");
    }

    if (t.getValue() == n) {
        return 0;
    }

    BinaryTreeNode<Integer> child = null;
    if (n < t.getValue()) {
        child = t.getLeft();
    } else {
        child = t.getRight();
    }

    return 1 + calculateDepth(child, n);
}

This specific case doesn't even use any helper functions, because it's simple enough to do without – there are only 4 paths through this code. Your previous implementation hid this by nesting conditionals when the other branch had already been terminated by a throw or return, and by unnecessary code duplication.

However, testing a recursion or loop can be difficult. While we could create a fairly complex tree and check for the correct result, we would like a way to check the loop invariant. In a language with higher-order functions, this might be:

public static int calculateDepth(
        BinaryTreeNode<Integer> t,
        int n)
{
    return calculateDepthLoop(t, n, calculateDepthLoop);
}

type Recurser = int(BinaryTreeNode<Integer>, int, Recurser);

private static int calculateDepthLoop(
         BinaryTreeNode<Integer> t,
         int n,
         Recurser recurse)
{
    if (t == null) {
        throw new TreeException("Value not found in tree!");
    }

    if (t.getValue() == n) {
        return 0;
    }

    BinaryTreeNode<Integer> child = null;
    if (n < t.getValue()) {
        child = t.getLeft();
    } else {
        child = t.getRight();
    }

    return 1 + recurse(child, n, recurse);
}

Now we could run a test plan like:

calculateDepthLoop(null, ANY, ANY) throws.

calculateDepthLoop(Tree(x, ANY, ANY), x, ANY) is0`.

calculateDepthLoop(Tree(x, left, ANY), y, callback) for y < x invokes result = callback(left, y, callback) and returns the result + 1.

calculateDepthLoop(Tree(x, ANY, right), y, callback) for x < y invokes result = callback(right, y, callback) and returns the result + 1.

with only 4 tests (one for each path) we can be sure that calculateDepthLoop() works as expected. We might want a couple more just to be sure that everything works for all valid values of x and y. Now we only need another test to check that everything integrates as it should, this can be done with a black-box test of calculateDepth(), which I'd do by creating a moderately complex tree requiring the function to recurse both left and right and return some value.


问:
Is return-type-(only)-polymorphism in Haskell a good thing?
One thing that I've never quite come to terms with in Haskell is how you can have polymorphic constants and functions whose return type cannot be determined by their input type, like

```<code>class Foo a where
    foo::Int -> a
</code>```

Some of the reasons that I do not like this:

Referential transparency:

"In Haskell, given the same input, a function will always return the same output", but is that really true? read "3" return 3 when used in an Int context, but throws an error when used in a, say, (Int,Int) context. Yes, you can argue that read is also taking a type parameter, but the implicitness of the type parameter makes it lose some of its beauty in my opinion.

Monomorphism restriction:

One of the most annoying things about Haskell. Correct me if I'm wrong, but the whole reason for the MR is that computation that looks shared might not be because the type parameter is implicit.

Type defaulting:

Again one of the most annoying things about Haskell. Happens e.g. if you pass the result of functions polymorphic in their output to functions polymorphic in their input. Again, correct me if I'm wrong, but this would not be necessary without functions whose return type cannot be determined by their input type (and polymorphic constants).

So my question is (running the risk of being stamped as a "discussion quesion"): Would it be possible to create a Haskell-like language where the type checker disallows these kinds of definitions? If so, what would be the benefits/disadvantages of that restriction?

I can see some immediate problems:

If, say, 2 only had the type Integer, 2/3 wouldn't type check anymore with the current definition of /. But in this case, I think type classes with functional dependencies could come to the rescue (yes, I know that this is an extension). Furthermore, I think it is a lot more intuitive to have functions that can take different input types, than to have functions that are restricted in their input types, but we just pass polymorphic values to them.

The typing of values like [] and Nothing seems to me like a tougher nut to crack. I haven't thought of a good way to handle them.

答:
I really wish the term "return type polymorphism" was never created.  It encourages a misunderstanding of what is happening.  Suffice it to say, while eliminating "return type polymorphism" would be an extremely ad-hoc and expressiveness killing change, it wouldn't even remotely resolve the issues brought up in the question.

The return type is in no way special.  Consider:

```<code>class Foo a where
    foo :: Maybe a -> Bool

x = foo Nothing
</code>```

This code causes all the same issues as "return type polymorphism" and demonstrates the same kinds of differences from OOP as well.  No one talks about "first argument Maybe type polymorphism" though.

The key idea is that the implementation is using types to resolve which instance to use.  The (run-time) values of any sort have nothing to do with it.  Indeed it would work even for types that have no values.  In particular, Haskell programs have no meaning without their types.  (Ironically, this makes Haskell a Church-style language as opposed to a Curry-style language.  I have a blog article in the works elaborating on this.)

OwnerDisplayName: dainichi

Body:
I really wish the term "return type polymorphism" was never created.  It encourages a misunderstanding of what is happening.  Suffice it to say, while eliminating "return type polymorphism" would be an extremely ad-hoc and expressiveness killing change, it wouldn't even remotely resolve the issues brought up in the question.

The return type is in no way special.  Consider:

class Foo a where
    foo :: Maybe a -> Bool

x = foo Nothing

This code causes all the same issues as "return type polymorphism" and demonstrates the same kinds of differences from OOP as well.  No one talks about "first argument Maybe type polymorphism" though.

The key idea is that the implementation is using types to resolve which instance to use.  The (run-time) values of any sort have nothing to do with it.  Indeed it would work even for types that have no values.  In particular, Haskell programs have no meaning without their types.  (Ironically, this makes Haskell a Church-style language as opposed to a Curry-style language.  I have a blog article in the works elaborating on this.)


答:
DRY is one of my favorite principles, and I often have a similar issue to yours.  How do I convince my co-workers (who are often very opinionated) that the way the code is now could be improved?

In my personal experience, if it means a lot to me I "just do it" on my own time in a branch.  When I'm happy with it, I bring it up with my colleague and show him what I mean rather than just talk about it.  My coworkers often don't like talking about doing things because "doing it is too much work".  If I show them something that's already done then they take to it a little more kindly :).

This question also looks close to yours, so it is probably worth reading.

Title: How can I sell DRY?

Body:
Where I work we have around 10 VS projects in a solution which are identical in functionality (with some different different rules in a few methods) and share many exact methods. They share the same namespace and the classes are called with if else's individually.

I believe it would be better and more succinct to have an interface and an abstract class with protected methods which are common among all the children.

The methods which take one of these classes can then take an Interface rather than have 10 different methods which take one and run the same method on each class.

The public methods all have the same signature and return the same thing.

Future implementations of the class will have a clear guideline on how to implement it (other than copy pasting and editing a previous version) and it is more maintainable. The reason I am considering this is because I am adding an extra version and unhappy with the idea of copying and pasting a lot of mess and changing all the bits I need to change (just in 2-3 long methods of ~20 methods)

I am having difficulty expressing my reasons to why I should be allowed to make these changes (would probably not take more than a day and changes no logic so minimal testing is required). I know intuitively it is better but that is not good enough!

How do I explain to the lead dev when DRY is a good thing? Or is he right that we should just keep copy and pasting things because we "inherited the code this way"?


问:
Is this the correct way to include this MIT licensed software in my software?
I'm using this script in one of my projects. It's licensed under MIT or Apache 2.

I've committed JSON.sh (as in, just the script) to my project, and copy+pasted the MIT license (as it appears in LICENSE.MIT) to the bottom of it.

Is that sufficient?

答:
Whether or not what you have done is sufficient depends on certain details of the JSON.sh project. As I write this (commit 2afb06) there are two major problems with the licensing of that project.

First, both licenses that the authors and contributors seem to want to use (ALv2 and MIT) are improperly applied; both require that each source file (and especially the JSON.sh file) contain certain text referring to the license (or the entire license, in the case of MIT). However, that was not done by any of the contributors.

Second, it is totally unclear whether the licensee (you) are free to choose which of the two licenses to use, or whether both must apply to JSON.sh. In programmer terms, are the two licenses "and"ed or "or"ed together? This matters because if the licenses both apply, then what you have done is not sufficient; you would have to include the Apache License v2 in its entirety in your source distribution, among other things.

I recommend that, since you are a developer, you submit 2 pull requests to the JSON.sh project. The first could add some license text to the JSON.sh file. The second could add an "or" in their README.md, to indicate that licensees have the choice of license. If your PRs are accepted, then the ambiguity disappears and your problem is solved!


答:
Start by telling (reminding) that cost to maintain software is exponential with its size (source this book).

Then your arguments look solid. Avoid clashing with their resist to change (because it's most likely just that) and gently guide them to a DRY version.

Title: How can I sell DRY?


问:
How to define fixed priced software projects and how to argue what is inside scope and what is outside scope?
So here is what happened

The customer gave me a list of things he wanted to have. It is a funding website. So to start a funding project he wanted to have certain fields in the "create/edit funding project" part. He gave me a document on what should get implemented.
I estimated around 25 hours for it and made a price tag for that milestone, but am now at 66 hours, and according to him, it is not done yet.

An example:
We changed an existing wordpress theme. He wanted a funding project initiator name for each project. So i estimated 0.5 hours for adding a field 'project initiator name'. For me, that was adding the field and adding it to the "create/edit funding project page" there was not mentioned to add it somewhere else in the document.

Now he added a "bug" that this new field does not change in the "My account" the display of the "my profile". He added other things that were not in the feature list as well.

How do you create contracts for milestones that don't give the customer a bad understanding of what is inside and me no need to explain what is not inside?

答:
Software is never done.  That's why it's soft.

If you sold this project as something that would be defect and maintenance free you're living in a hell of your own making.

A lack of defect tickets is not a milestone.  It's a temporary anomaly (that may indicate something is wrong with the ticketing system).

You should be working towards the previously agreed milestones.  Doing anything beyond that is not only hurting you it's hurting your customer who now thinks they have to hound you over every little thing when what they need is a working web site.  You understand this better then your customer does.  It's your responsibility to make it happen.

Your contract should have excluded maintenance and defect corrections.  If the site can be made to work then you've got your milestones.  You drive this point home by showing them what maintenance and defect corrections are going to cost.  Don't underestimate this just to make work for yourself.  This isn't real work.  This isn't even charity.  You're hurting your customer.

When you estimate the work make the scope clear and the price clear.  Stick to the scope and the price.  If there is any doubt be very conservative.  Taking longer than estimated to get it "just right" is unprofessional.

Sometimes you get surprised.  It happens.  But as soon as it happens revise your estimate and seek new approval.  Do not work without approval.

Do not "try harder".  The very moment your estimate is in the slightest doubt revise it.

This is behaving professionally.  Customers like predictability.  So much they will pay you to take an hour to do a 5 minute job.  Take 65 minutes to do it though and don't expect them to hire you again.

You say this is a fixed price contract.  Doesn't matter.  Time is money.  Also, you are a very valuable resource to your customer so working yourself raw over trivia is also not doing them any favors.  Take care of yourself.  Take care of your customer.

If you understand this and behave like this then when problems crop up that you think will take "0.5 hours" to fix you can answer them with a confident, "That will require a new agreement.  I'll allow a day for it and I'll need you to be available just to be sure it's resolved to your satisfaction."

Do that every time some little thing comes up and you'll see the little things become fewer and fewer and a bit more important.

Many programmers think of their customers as slave drivers cracking a whip demanding, "Faster! Faster!"

This is all wrong.  Think of them as a little kid in the back seat of an airplane that you are piloting as they squeal, "Faster! Faster!"

It's your job to land them safely.  You can laugh and dip your wings.  But mind your air speed.


问:
How to review code that you do not understand?
I have been given the role to improve development in our company. The first thing I wanted to start was code reviews since that has never been done here before.

There are 3 programmers in our company. I am a web programmer, my known languages are mainly PHP, ActionScript and JavaScript. The other 2 developers write internal applications in VB.net

We have been doing code reviews for a couple weeks now. I find it hard to understand VB code. So when they say what its doing, for the most part I just have to take their word for it.

If I do see something that looks wrong, I explain my opinion and I explain how I would address it in one of the languages I know.

Sometimes my suggestions are welcomed but many times I am told things like "this is the best way of doing it in this language" or "that doesn't apply to this language" or similar things of that nature.

This may be true, but without knowing the language I am not sure how to confirm or refute these claims.

I know one possible solution would be to learn vb so I can do better code reviews. I really have no interest in learning vb (especially since I have a list of other technologies I am trying to learn for my own projects) and would like to keep this as a last resort but it is an option.

Another idea that came to me is, they both have interest in C# and so do I. Its relative to them because its .net and relative to me because its more similar to the languages I know. Yet it is new to all of us. I thought about the benefits of us all collaborating on a pet C#.net project and reviewing each others code from that.

I guess theres also the possibility hiring a consultant to come in and give us some code reviews.

What would you recommend I do in this situation.

答:
Even if you learn the basics of VB, performing a code review while not knowing all of the features of the language will not enable you to detect the usage of insecure features in the language.

Suppose that you weren't aware that the input() function in Python 2 actually evaluated the input before returning it, in order to make it easier to parse non-string input types.  Then the code would be vulnerable to Arbitrary Code Execution, allowing the user to enter something like __import__('os').execl('/bin/sh', '/bin/sh') on a Linux system to turn the Python process into a shell.  Instead, raw_input() should be used to get the unprocessed input data.

Attempting to perform a code review while not aware of all of the features of the language could not only prevent you from realizing a better way to do a certain procedure in the language; it could also lead to detrimental security flaws.


答:
Come up with an incremental transition plan. That is, make it so the project is always in a runnable state, transitioning from old code to new code without getting in the position of requiring effectively all of the new code to be written first before anything works.

There might be some things still done "the old way," while other features are done "the new way," and the user interface might be less than desirable for a while. But this approach will significantly reduce your risk, because you can always ship something. (Actually, if you have a gradual UI transition too, this might work nicely with Joel's notion of the Iceberg Effect: management/customers will see progress and have a notion of what remains to be done.)

This depends somewhat on the circumstances of your code base, but look carefully before deciding if this base is the exception to the rule or not, because it probably isn't.

Title: What are important things to remember when reengineering a legacy application?

Body: About to embark on the initial phases of a project to rewrite a legacy application from the ground up (existing business rules will change somewhat, and be extended to incorporate a large number of new requirements that the existing infrastructure cannot handle). I am looking for items that are important to remember when working to reengineer an existing application.</p>


问:
Does exist a reflexive compiled language?
I just wonder if exists a compiled language that can modify it's own machine code.

I know that in most common operative systems the executable code is protected during execution time, but maybe if you're using some specific a permissive operative system, you can use a language that allow you use reflexive features over it's own code.

I found that some assembly programmers used reflexivity so maybe someone invented some high level language that allows you to compile reflexive machine code.

UPDATE
The real case
We are building a high performance scientific program. We are using in C as a portable assembly. We usually check the generated assembly code to improve our code making it faster. Looking inside we figured that a good way to improve the code is that C have some facilities of machine code reflexivity.

Example:
Imagine this code:

```<code>void func (int b) {
int i;
for ( i = 0 ; i < 10 ; i ++) {
  if ( i + b == 2 ) do_some();
  do_other();
}
</code>```

Would be more performant if you could make a reflexive approach

```<code>void util(int i, int b) {
  if ( i + b == 2 ) {
    do_some();
    delete_util(); //this will delete the util function and just continue where is called.
  }
}

void func(int b) {
int i;
for ( i = 0 ; i < 10 ; i ++) {
  util(i, b);
  do_other();
}
</code>```

I know there are a lot of reflexive languages that are interpreted or compiles to VMs, but because of that are less performant, then not what I need.

答:
First of all, while most modern operating systems prevent writing to code by default, all common systems provide a way of overriding this behaviour. This is necessary if you want to use a language or environment that has a JIT compiler (e.g. Java, .Net, node.js, etc.). So you don't need a specific os for this.

Secondly, many existing languages provide facilities for this, although the facilities vary in ease of use radically. For example, both the .net framework and Java virtual machines support libraries that effectively allow you to produce new classes that contain code generated using the assembly language representation of their virtual machine Instruction sets. Other languages, e.g. Javascript and Ruby provide a mechanism usually called "eval" that will take a string of text in the language itself and execute it. This is commonly thought of as a facility primarily of interpreted languages, but many languages originally intended to be interpreted can now be compiled to native code, so the distinction is less than you might think.

Lisp (and derivatives like Scheme and Clojure) takes a third approach: code has the same structure as data in these languages, and can be directly manipulated. This similarity of structure is called Homoiconicity and is a very useful property of languages for programs that manipulate code directly. Again, many such languages are compiled to native code prior to execution.