问:
Why was Scala not implemented with C or C++
Does anybody know why was Scala implemented in Java and .NET instead of C or C++? Most languages are implemented with Cor C++ [i.e Erlang, Python, PHP, Ruby, Perl]. What are the advantages for Scala implemented in Java and .NET other than giving access to Java and .NET libraries?

UPDATE

Wouldn't Scala gain more benefit if it were implemented in C because it can be tuned better rather than relying on JVM?

答:
C code is statically compiled to native code (machine code).

Scala is statically compiled to java bytecode and then, as required, dynamically compiled to optimised native code.  The process:

Scala code ---statically-compiled-to---> JVM byte code ---dynamically-compiled-by-JVM-Hotspot-to---> native code

General options for building / running any language:

a) interpret source code directly via a runtime interpreter engine

b) statically compile code to native code (possibly via intermediate stages e.g. source -> C -> native)

c) statically compile source code to lower-level intermediate code, and interpret it at runtime

d) statically compile source code to lower-level intermediate code, then use initial interpretation, followed by dynamic compilation and optimisation techniques to convert to native code.  Code is interpreted until typical execution paths and bottlenecks are found, then code is compiled for fastest execution under typical conditions.  It's recompiled/retuned when execution conditions change enough to warrant this

Your Question: "Why does Java use (d) with a JVM, rather than (b) with C intermediate code?"

Answer:

Firstly, observe that Scala's a much higher level language than C, giving programming power, ease of programming and conciseness.  It's about '1 level higher' than Java due to first class & higher order functions, implicit functions, functions as objects, closures and currying, support for tail-recursion compiling to fast stack-conserving loops, everything as objects, all operators as methods which can be (re-)defined in libraries, case classes and reduction (pattern matching), implicit type derivation, stronger polymorphism through expanded multi-inheritable traits and expanded generics, built-in syntax for pairs & tuples & cons (lists & trees) & maps, support for immutabile data structures, support for powerful 'reactive' parallel and concurrent computing with message copying and passing between actors, advanced support for arbitrary domain-specific DSLs, scriptability, and the REPL. Java's about '1 level higher' than C due to object-orientation, pointer management and garbage collection, string support, multi-threading support and concurrency control, plus standard API libraries.

Performance: For a high level language, (d) gives faster performance than (a)-(c).

Directly written and hand-optimised C code is fast.
However, higher-level languages statically compiled to C are relatively slow.  The java designers knew this well.  Their current "Hotspot" design boosts performance by up to order of magnitude.  On a single core, Java HotSpot code is on average '50% as fast' as human-optimised C (in the best it's case '120% as fast', in the worst case '30% as fast').  But of course that's comparing apples with oranges - low-level code v high-level code.  And that would be much worse if Hotspot optimisation wasn't used. To confirm, just disable hotspot compilation via JVM args!  Or consider java 1 & 2 performance, when hotspot didn't exist or was immature. Or try compiling another language via C - e.g. perlcc.  So the above are great results for a powerful and productive language.  With further development, it's possible (or even likely) that JVM may soon outpace hand-coded C on average.
Scala is merely 70-80% as slow as java on average.  But scala strongly scales across multiple cores (with further improvements to be ongoing), whereas java does partially and C doesn't.  Single Core performance for such high-level languages is rated:

interpreteted < statically compiled < dynamically compiled

Multi-Core performance/scalability is rated:

interpreted dynamic code < statically compiled imperative code < statically compiled functional / declarative code < dynamically compiled functional / declarative code

This puts scala in the winning seat because processor speed has hit it's limit and now the number of cores are increasing by Moore's law. Scala's very fast on multi-cores and in future, could become several times faster than C or java.  Compiling statically to C is clearly not the fastest option.

Interoperability: languages on a widely supported VM have better language interoperability than 'isolated' languages.  Scala "automatically plays with" java classes, interfaces and objects by simply importing them and using them as if they were scala classes, traits and objects.  Similar is possible with other JVM languages such as Groovy, Clojure, JRuby and JPython - with ease of interoperability dependent upon how cleanly each language was made to compile to understandable & usable java runtime classes/interfaces/objects.  That much comes for 'free' (as in 'close to').  Scala interoperates with C via JNA, the successor to JNI - which comes with some effort, but the tools have been quite well streamlined over time.  JNA can actually interoperate with compiled native code from any arbitrary language - but you must know the exact structure of compiled datatypes and functions.  If not, you can use a C wrapper object (or in the worst case, chain an additional 'C to other language' mechanism),  to interoperate with Objective C, C#, Perl, Ruby, Cobol, etc.

Portability: JVM runs on dozens of operating system platforms / versions 'out of the box'.  Scala is automatically ported to these.  Noted exception is iOS (iPad/iPhone/iPod) - blocked 'commercially', rather than 'technically' by Apple.  This couldn't have been anticipated 12 years previously, during initial design of JVM.  JVM runs fine on dozens of other servers, desktops, mobiles and embedded devices, including ones that don't support C - including Android with Google adapted Dalvik VM (50%+ of new phones sold). Sure, C code works on a multitude of platforms, so may be rated 'up there with or probably beyond' Java (notably, C is a subset of Objective-C).  But C would come at the cost of (1), (2) & (3).  Of course, HTML5/javascript/webkit (or objective-C) presentation layer on iOS can interoperate with a remote scala app - so developer's should very much do that.  Of course, they'll be less productive.

Tools and Libraries: Obviously there are thousands of commercial and open-source Java libraries and tools that can leverage / be leveraged by Scala - more than for C.

Security: - running on a controlled app server or JVM environment gives stronger support for security policies and restrictions, which can be highly valuable in a corporate environment.


问:
Why does the Git community seem to ignore side-by-side diffs
I used to use Windows, SVN, Tortoise SVN, and Beyond Compare.  It was a great combination for doing code reviews.

Now I use OSX and Git.  I've managed to kludge together a bash script along with Gitx and DiffMerge to come up with a barely acceptable solution.

I've muddled along with this setup, and similar ones, for over a year.  I've also tried using the Github diff viewer and the Gitx diff viewer, so it's not like I've not given them a chance.

There are so many smart people doing great stuff with Git. Why not the side-by-side diff with the option of seeing the entire file?  With people who have used both, I've never heard of anyone that likes the single +/- view better, at least for more than a quick check.

答:
From my personal usage, I think the answer is mostly that diffs are short enough that it doesn't matter.

For code reviews, I use a full-featured code-review tool, that gives me all the things I like - like comments, syntax highlighting, and side-by-side view.

I use git diff almost exclusively during when staging code to commit; When that's the case, the diffs are small enough, and recent enough, that I don't need to see the context to remember what's going on.

My code-review tool of choice Phabricator, or possibly IDE-integrated tools, that are language context-aware.
I think github's pull-request flow is terrible for code-review, mostly because it shows unified diff and not side-by-side.

ContentLicense: CC BY-SA 3.0


问:
Best way to store motion changes to reduce memory
I am comparing jpeg to jpeg in a constant 'video-stream'. I am using EMGU/OpenCV to compare each pixels at the byte level. There are 3 channels to each image (RGB). I have heard that it is common practice to store only the pixels that have changed between frames as a way of conserving memory space. But, if for instance, I say EVERY pixel has changed (Please note I am using an exaggerated example to make my point and I would normally discard such large changes.) then the resultant bytes saved is 3 times larger than the original jpeg.

How can I store such motion changes efficiently?

答:
Have a bit that indicates whether you are storing changes from the last frame or a new frame and store whatever option is less memory consuming.

You can store either a jpeg (or any other format really, if possible for your purpose since jpeg is far for optimal for that) of the image that represents the changes or a simple jpeg of the next frame, and indicate using an added bit which format you used.

Obviously, you may (and according to your comments seem to) have constrains which block you from using this approach. In any case, this is more or less the approach used in the MPEG video format(s).

Look up I frames ("Intra coded frames/slices") and P frames ("Predicted frames/slices") in this Wikipedia article - Video compression picture types


问:
Reference vs dereference pointers in arguments C++/C
OK, I'm facing this all the time in many functions I write, which should I use?

```<code>void sth(int* a)
void sth(int& a)
</code>```

Which one is faster, regarding two separate occasions: a is a small variable or a is a large data struct.

I would like a deep answers with pertinence to the actual hardware and stack process.

答:
Most compilers will implement references as pointers. So the deep answer to your question is that there will be absolutely no difference in terms of performance between the two. (Doesn't change aliasing analysis either as far as I know.)

If you want to be 100% sure of that statement, inspect your compiler's output.

```<code>struct Small {
    int s;
};
void foo(Small* s)
{
    s->s = 1;
}
void bar(Small& s)
{
    s.s = 1;
}
</code>```

Compiled with clang++ -O2, saving the assembly:

```<code>_Z3fooP5Small:                          # @_Z3fooP5Small
    .cfi_startproc
# BB#0:
    movl    $1, (%rdi)
    ret
_Z3barR5Small:                          # @_Z3barR5Small
    .cfi_startproc
# BB#0:
    movl    $1, (%rdi)
    ret
</code>```

You can try that with a large struct or an enormously complex struct - doesn't matter, all you're passing in to the function is a pointer.

That being said, there are semantic differences between the two. The most important one being that, as long as your program is free of undefined behavior, the overload that takes a reference is guaranteed to get a reference to a valid, live object. The pointer overload isn't.

Also assigning to s in these two examples has completely different meanings. It would replace the pointer in the first function (i.e. whatever it pointed to remains unchanged, but becomes unreachable from within that function; caller unaffected by the assignment).

In the second, it would call the appropriate assignment operator en the object passed in (effect visible from the caller).

So your choice shouldn't be made on a potential performance difference (there will generally be none), but on semantics. What you need the function to be able to do, and how you should be able to call it, will dictate what overload(s) you need to provide.

Body:
Most compilers will implement references as pointers. So the deep answer to your question is that there will be absolutely no difference in terms of performance between the two. (Doesn't change aliasing analysis either as far as I know.)

If you want to be 100% sure of that statement, inspect your compiler's output.

struct Small {
    int s;
};
void foo(Small* s)
{
    s->s = 1;
}
void bar(Small& s)
{
    s.s = 1;
}

Compiled with clang++ -O2, saving the assembly:

_Z3fooP5Small:                          # @_Z3fooP5Small
    .cfi_startproc
# BB#0:
    movl    $1, (%rdi)
    ret
_Z3barR5Small:                          # @_Z3barR5Small
    .cfi_startproc
# BB#0:
    movl    $1, (%rdi)
    ret

You can try that with a large struct or an enormously complex struct - doesn't matter, all you're passing in to the function is a pointer.

That being said, there are semantic differences between the two. The most important one being that, as long as your program is free of undefined behavior, the overload that takes a reference is guaranteed to get a reference to a valid, live object. The pointer overload isn't.

Also assigning to s in these two examples has completely different meanings. It would replace the pointer in the first function (i.e. whatever it pointed to remains unchanged, but becomes unreachable from within that function; caller unaffected by the assignment).

In the second, it would call the appropriate assignment operator en the object passed in (effect visible from the caller).

So your choice shouldn't be made on a potential performance difference (there will generally be none), but on semantics. What you need the function to be able to do, and how you should be able to call it, will dictate what overload(s) you need to provide.


答:
The main semantic differerence between int* and int& is that the former allows passing of NULL or uninitialized values, and the latter does not. So the implementation of a  function using pointers should look like this:

```<code> void sth(int* a)
 {
     if(a==NULL)
     {
         // handle NULL case
     }
     else
     {
         // do something with *a
     }
 }
</code>```

When using references, you can omit that special NULL handling within the function.

So if the function you are going to write does not explicitly has a special need to allow NULL values as input, use int&. See also this Wikipedia entry.

Note that you should not make your decision based on which of the 2 alternatives is faster. Your first priority should be correct code, not any micro-optimizations, which I would expect in this case to be neglectable.

Title: Reference vs dereference pointers in arguments C++/C

Body:
OK, I'm facing this all the time in many functions I write, which should I use?

```<code>void sth(int* a)
void sth(int& a)
</code>```

Which one is faster, regarding two separate occasions: a is a small variable or a is a large data struct.

I would like a deep answers with pertinence to the actual hardware and stack process.

Body:
The main semantic differerence between int* and int& is that the former allows passing of NULL or uninitialized values, and the latter does not. So the implementation of a  function using pointers should look like this:

 void sth(int* a)
 {
     if(a==NULL)
     {
         // handle NULL case
     }
     else
     {
         // do something with *a
     }
 }

When using references, you can omit that special NULL handling within the function.

So if the function you are going to write does not explicitly has a special need to allow NULL values as input, use int&. See also this Wikipedia entry.

Note that you should not make your decision based on which of the 2 alternatives is faster. Your first priority should be correct code, not any micro-optimizations, which I would expect in this case to be neglectable.


答:
References are converted to pointers by the compiler so at run time there is no difference in speed. Speed is not the reason you choose references instead of pointers but in fact references might be a bit faster in your overall code simply because you don't need to constantly check for invalid references (NULL pointers).

If a is a small variable (no larger than the machine address size), then there is no difference between a and &a. If a is larger than the machine's address size (e.g. a class object) then &a is faster and &a must be done (rather than a).

Of course you need to consider whether you want to be able to edit a in the called function. If a is large and you want to forbid changing of a, pass a constant reference to a.

If using C++, you should always use references when possible. A good C++ book will list what the difference between references and pointers are. You should consider the following:

References are implemented underneath as pointers. So why use a reference? Because it allows the function writer to determine how a function works without affecting how it is called. With references, the caller of a function doesn't need to know if the function takes a pointer or the object itself. For example, you call the following 2 functions the same way and notice that we can change add1 to use references without affecting all the callers:

```<code>int add1 (int a, int b);
int add2 (int &a, int &b) {
// this actually gets converted by the compiler to
// *a + *b
    return a + b;
}
</code>```

If you were using pointers, you'd have to know that the function is actually taking the address, not the object itself. In other words, references add to information hiding.

So to sum up, references are just syntactic sugar. The compiler will convert all references to pointers and operation to references to valid operations with/on pointers.

Second, unlike pointers - a reference is the object. With pointers, you can change the object pointed to or you can change the pointer itself (in which case it will point to something else). With a reference there's only one thing you can change - the referred object.

Third, references cannot be re-assigned to refer to another object like a pointer can. Often, in linked lists you have to move pointers forward/backwards. You can't do this with a reference. Think of a reference as an alias to an object.

Lastly, about the NULL...in C code you will see a lot of NULL pointer checking. References are meant to help with that by allowing the compiler to catch whenever a reference doesn't refer to a valid object. The C++ standard also says that a reference cannot point to an invalid object (e.g. a NULL). However, I think it's up to the compiler on how it implements that so you need to double check with your compiler. I think some compilers will not even warn you.

Body:
References are converted to pointers by the compiler so at run time there is no difference in speed. Speed is not the reason you choose references instead of pointers but in fact references might be a bit faster in your overall code simply because you don't need to constantly check for invalid references (NULL pointers).

If a is a small variable (no larger than the machine address size), then there is no difference between a and &a. If a is larger than the machine's address size (e.g. a class object) then &a is faster and &a must be done (rather than a).

Of course you need to consider whether you want to be able to edit a in the called function. If a is large and you want to forbid changing of a, pass a constant reference to a.

If using C++, you should always use references when possible. A good C++ book will list what the difference between references and pointers are. You should consider the following:

References are implemented underneath as pointers. So why use a reference? Because it allows the function writer to determine how a function works without affecting how it is called. With references, the caller of a function doesn't need to know if the function takes a pointer or the object itself. For example, you call the following 2 functions the same way and notice that we can change add1 to use references without affecting all the callers:

int add1 (int a, int b);
int add2 (int &a, int &b) {
// this actually gets converted by the compiler to
// *a + *b
    return a + b;
}

If you were using pointers, you'd have to know that the function is actually taking the address, not the object itself. In other words, references add to information hiding.

So to sum up, references are just syntactic sugar. The compiler will convert all references to pointers and operation to references to valid operations with/on pointers.

Second, unlike pointers - a reference is the object. With pointers, you can change the object pointed to or you can change the pointer itself (in which case it will point to something else). With a reference there's only one thing you can change - the referred object.

Third, references cannot be re-assigned to refer to another object like a pointer can. Often, in linked lists you have to move pointers forward/backwards. You can't do this with a reference. Think of a reference as an alias to an object.

Lastly, about the NULL...in C code you will see a lot of NULL pointer checking. References are meant to help with that by allowing the compiler to catch whenever a reference doesn't refer to a valid object. The C++ standard also says that a reference cannot point to an invalid object (e.g. a NULL). However, I think it's up to the compiler on how it implements that so you need to double check with your compiler. I think some compilers will not even warn you.


问:
Is there much difference between X86 Assembly language on Windows and Linux?
I'm a complete beginner at Assembly, and my aim is to learn as much as I can to do with Assembly to one day I can reach expert level (I know I'm way off right now, but you never know). My only problem is this: I've got two books which both teach assembly, one on a Linux and the other on Windows. They are Jeff Duntemann's Assembly Language Step By Step (the linux one) and Introduction to 80x86 Assembly Language and Computer Architecture (the windows version). If I want to get the best out of assembly, should I do this on linux and windows? Also, is the syntax the same on Windows and Linux or will I have teach my self again when learning on the other OS( which is my main concern, I want to be able to use assembly on windows and linux).</p>

答: Linux tends to favour AT&T style x86 assembly code for some reason. It's quite awful. For doing Windows development you probably use Visual Studio which supports the far more readable Intel style syntax. Sample code from Intel uses this style too generally. Note that you cannot write inline assembly for 64 bits apps with Visual Studio, it works only for 32 bit apps. 64 bit apps are expected to use intrinsics instead. I don't believe gcc has this restriction.</p>


问:
What would be the market life of a JVM based software framework?
I saw how Struts 1 lasted from 2000 to 2013. I hear that people are moving from Struts 2 to Spring. But for a project that may need to be maintained for a decade or two, would it be advisable to opt for a framework or directly code with servlets and jquery? Can a system architecture really be designed keeping in mind a particular framework?

What really is the market life of a framework? Do the creators of the framework create it with the assumption that it would become obsolete in a decade?

答:
My advice is to evaluate JVM web frameworks based on ~20 criteria that are important to you and your application. This includes technical categories (e.g. supports RESTFul, Ajax, i18n) and non-technical categories (e.g. Strength of community, number of books etc). Score each category (with weightings on categories that are more important to you) and pick the two winners.

Then prototype the top two, picking a problem that you know is risky/difficult for your project.

Matt Raible is the guy who taught most of us this approach, see him in action here:


问:
Organisation GitHub account. Secure to use for personal projects?
So a large client of mine gave me access to their Organisation GitHub account.

With it came a login for myself (on github.companyname.com) and of course access to certain repos on their company account (by switching the user to the company via the button in the top left).

Now I was wondering, since I can create private repos for myself, is it safe for me to use these for non-related projects or can the company administrators access my user's repos despite being private? My understanding of Github is limited as it is, so this extra layer of complexity from the organisation account isn't helping too much.

Thanks,
Mike

UPDATE: Thanks to all of you who posted answers and wrote comments, all were really helpful. I have decided to no host any personal projects on their enterprise account as suggested, and again, as recommended I now host my repos on a private provider like bitbucket.

Mike

答: Not unless you add keys from the company (i.e. not yours) to your own github project as collaborators. </p>


问:
How to keep your third party libraries up to date?
Let's say that I have a project that depends on 10 libraries, and within my project's trunk I'm free to use any versions of those libraries. So I start with the most recent versions. Then,  each of those libraries gets an update once a month (on average). Now, keeping my trunk completely up to date would require updating a library reference every three days.

This is obviously too much. Even though usually version 1.2.3 is a drop-in replacement for version 1.2.2, you never know without testing. Unit tests aren't enough; if it's a DB / file engine, you have to ensure that it works properly with files that were created with older versions, and maybe vice versa. If it has something to do with GUI, you have to visually inspect everything. And so on.

How do you handle this? Some possible approaches:

If it ain't broke, don't fix it. Stay with your current version of the library as long as you don't notice anything wrong with it when used in your application, no matter how often the library vendor publishes updates. Small incremental changes are just waste.

Update frequently in order to keep change small. Since you'll have to update some day in any case, it's better to update often so that you notice any problems early when they're easy to fix, instead of jumping over several versions and letting potential problems to accumulate.

Something in between. Is there a sweet spot?

答:
I evaluate.

Firstly I look for bugs that we've raised against that library and see if they've been fixed.

Secondly I look for any other bug fixes in the lib that we could benefit from (perhaps something that is a possible corner case).

Thirdly I look for improvements in the lib/API and then investigate the impact of changing our code to utilise that and the benfit tradeoff.  I've all too often in the past upgrade libs without actually utilising their new features, silly really!

I then weigh all of that up against staying with the existing lib.

Always test - hopefully your unit/integration tests will ensure that no major regressions occur.

ContentLicense: CC BY-SA 2.5


问:
For asp.net mvc is this a three tiered solution?
I am a asp.net mvc programmer and if I want to start a project I do this:

I make a class library named Model for my models.

I make a class library named Infrastructure.Repository for database processes

I make a class library named Application for business logic layer

And finally I make a MVC project for the UI.

But now some things are confusing me.

Am I using 3-tier programming?
If yes so what is n-tier programming and which one is better?
If no so what is 3-tier programming?

Some where I see that the tiers namings are DAL and BIZ.

Which one is correct according to the naming convention?

答:
This is not a complete answer but it addresses one important point. Namely the difference between layers and tiers.

"It is important to understand the distinction between layers and tiers. Layers describe the logical groupings of the functionality and components in an application; whereas tiers describe the physical distribution of the functionality and components on separate servers, computers, networks, or remote locations. Although both layers and tiers use the same set of names (presentation, business, services, and data), remember that only tiers imply a physical separation. It is quite common to locate more than one layer on the same physical machine (the same tier). You can think of the term tier as referring to physical distribution patterns such as two-tier, three-tier, and n-tier..." for more see: MSDN-Layered Application Design.


问:
Is this high coupling?

Question

I'm currently working a on an assignment for school. The assignment is to create a puzzle/calculator program in which you learn how to work with different datastructures (such as Stacks). We have generate infix math strings suchs as "1 + 2 * 3 - 4" and then turn them in to postfix math strings such as "1 2 + 3 * 4 -".

In my book the author creates a special class for converting the infix notation to postfix. I was planning on using this but whilst I was about to implement it I was wondering if the following is what you would call "high coupling". I have read something about this (nothing that is taught in the book or anything) and was wondering about the aspect (since I still have to grasp it).

Problem

I have created a PuzzleGenerator class which generates the infix notation of the puzzle (or math string, whatever you want to call it) when it's instantiated. I was going to make a method getAnswer() in which I would instantiate the InToPost class (the class from the book) to convert the infix to postfox notation and then calculate the answer. But whilst doing this I thought: "Is using the InToPost class inside this method a form a high coupling, and would it be better to place this in a different method?" (such as a "convertPostfixToInfix" method, inside the PuzzleGenerator class)

Thanks in advance.

答:
No, it would not be high coupling -- no more than to use any library class within another class.

It is coupling, of course, because it's a dependency. High coupling occurs when there are too many direct dependencies between classes and you lose the ability to recycle your code. For example, if you have a LogWriter class which has only one method: Log( String ), you may use a specific class for outputting a log, such as a file writing class.

The above would be high coupling because you can't reuse the LogWriter class in other output modes. The job of the LogWriter class is to create log line and output them, not specifically log to the file system.

In that case it would be better to inject the dependency in the constructor, by passing it: you would have a LogWriter( OutputStream ) constructor which stores and reuses the stream to output the log.

Another possible way is to read a configuration file and compose the class from it using reflection.

Title: Is this high coupling?


答:
I would avoid this -- there are some access / code security issues that are solvable by nothing more complex then having something purely under your control checking out a copy every day but the thornier issue is intellectual property. If it is on the company's account they have a much stronger claim to ownership than if it is under your account. I would not want to open that can of worms myself.

I'll add that bitbucket lets you do unlimited priviate git repositories for free if you just are trying to find a free cloud DCVS provider.

Title: Organisation GitHub account. Secure to use for personal projects?

Body:
So a large client of mine gave me access to their Organisation GitHub account.

With it came a login for myself (on github.companyname.com) and of course access to certain repos on their company account (by switching the user to the company via the button in the top left).

Now I was wondering, since I can create private repos for myself, is it safe for me to use these for non-related projects or can the company administrators access my user's repos despite being private? My understanding of Github is limited as it is, so this extra layer of complexity from the organisation account isn't helping too much.

Thanks,
Mike

UPDATE: Thanks to all of you who posted answers and wrote comments, all were really helpful. I have decided to no host any personal projects on their enterprise account as suggested, and again, as recommended I now host my repos on a private provider like bitbucket.

Mike


问:
Languages like Tcl that have configurable syntax?
I'm looking for a language that will let me do what I could do with Clipper years ago, and which I can do with Tcl, namely add functionality in a way other than just adding functions.

For example in Clipper/(x)Harbour there are commands #command, #translate, #xcommand and #xtranslate that allow things like this:

```<code>#xcommand REPEAT;
   => DO WHILE .T.
#xcommand UNTIL <cond>;
  =>     IF (<cond>);
             ;EXIT;
         ;ENDIF;
     ;ENDDO

LOCAL n := 1
REPEAT
    n := n + 1
UNTIL n > 100
</code>```

Similarly, in Tcl I'm doing

```<code>proc process_range {_for_ project _from_ dat1 _to_ dat2 _by_ slice} {
    set fromDate [clock scan $dat1]
    set toDate   [clock scan $dat2]

    if {$slice eq "day"} then {set incrementor [expr 24 * 60]}
    if {$slice eq "hour"} then {set incrementor 60}

    set method DateRange

    puts "Scanning from [clock format $fromDate -format "%c"] to [clock format $toDate -format "%c"] by $slice"
    for {set dateCursor $fromDate} {$dateCursor <= $toDate} {set dateCursor [clock add $dateCursor $incrementor minutes]} {
        # ...
    }
}
process_range for "client" from "2013-10-18 00:00" to "2013-10-20 23:59" by day
</code>```

Are there any other languages that permit this kind of, almost COBOL-esque, syntax modification?

If you're wondering why I'm asking, it's for setting up stuff so that others with a not-as-geeky-as-I-am skillset can declare processing tasks.

答:
Lisp macros are probably a good examples of the kind of feature you are looking for. They basically allow you to extend the language in relatively arbitrary ways.

Effectively, a macro is a function that gets executed at compile time, and can produce whatever code you like. Lisps are well suited to this kind of technique because they are homoiconic - which means that code is itself expressed in Lisp data structures. So your macro just needs to produce a data structure that represents the code that you want.

Here's an example from Clojure that adds a C-style for loop to the language:

```<code>(defmacro for-loop
  "Runs an imperative for loop, binding sym to init, running code as long as check is true,
  updating sym according to change"
  ([[sym init check change :as params] & code]
    `(loop [~sym ~init value# nil]
       (if ~check
         (recur ~change (do ~@code))
         value#))))

(for-loop [i, 0, (< i 10), (inc i)]
  (println i))
=> prints the numbers from 0 to 9 inclusive as you would expect
</code>```

As you can see - it only takes a few lines of code to add a new language construct.

One caveat: this is a powerful technique and should be used with care. In general, you shouldn't use a macro when a normal function would do the job.

Body:
Lisp macros are probably a good examples of the kind of feature you are looking for. They basically allow you to extend the language in relatively arbitrary ways.

Effectively, a macro is a function that gets executed at compile time, and can produce whatever code you like. Lisps are well suited to this kind of technique because they are homoiconic - which means that code is itself expressed in Lisp data structures. So your macro just needs to produce a data structure that represents the code that you want.

Here's an example from Clojure that adds a C-style for loop to the language:

(defmacro for-loop
  "Runs an imperative for loop, binding sym to init, running code as long as check is true,
  updating sym according to change"
  ([[sym init check change :as params] & code]
    `(loop [~sym ~init value# nil]
       (if ~check
         (recur ~change (do ~@code))
         value#))))

(for-loop [i, 0, (< i 10), (inc i)]
  (println i))
=> prints the numbers from 0 to 9 inclusive as you would expect

As you can see - it only takes a few lines of code to add a new language construct.

One caveat: this is a powerful technique and should be used with care. In general, you shouldn't use a macro when a normal function would do the job.


答:
There are many languages out there that are quite flexible. Many (often newer) languages pride themselves in their suitability for domain-specific languages (DSLs). However, some of your examples need some macro system.

Some languages that prominently use macros:

Lisp and descendants. These work as abstract syntax tree (AST) substitutions.

C, C++. The C preprocessor uses token-level subtitution, and is less powerful than Lisp macros. Your first example can be directly translated to C macros:

```<code>// untested
#define repeat for(;;) {
#define until(cond) if(cond) break; }

auto n = 1;
repeat {
  n++;
} until(n > 100)
</code>```

Many languages allow functions to be called with keywords. Examples include

Lisps like Common Lisp.

Smalltalk and descendants.

Python:

Some languages have syntax that allow to fake named arguments, e.g.

many command-line interfaces:

```<code>git commit --file=foo.txt --message="Some fixes" --author=me
</code>```

Any language with dictionary literals

Perl.

Javascript: foo.bar({ x: 42, y: somethingElse }).

Languages that have function literals/lambdas/closures don't need macros to define new control flow.

Any functional language, e.g. Lisps, ML

Smalltalk and descendants. Especially noteworthy is Ruby with its ubiquitous do ... end blocks.

With clumsy syntax: C++11, Perl, Javascript.

There are some languages that have a flexible view on operators, so that a lot of punctuation like parens for function calls etc. can be left out. An example would be Scala.

Title: Languages like Tcl that have configurable syntax?

Body:
I'm looking for a language that will let me do what I could do with Clipper years ago, and which I can do with Tcl, namely add functionality in a way other than just adding functions.

For example in Clipper/(x)Harbour there are commands #command, #translate, #xcommand and #xtranslate that allow things like this:

```<code>#xcommand REPEAT;
   => DO WHILE .T.
#xcommand UNTIL <cond>;
  =>     IF (<cond>);
             ;EXIT;
         ;ENDIF;
     ;ENDDO

LOCAL n := 1
REPEAT
    n := n + 1
UNTIL n > 100
</code>```

Similarly, in Tcl I'm doing

```<code>proc process_range {_for_ project _from_ dat1 _to_ dat2 _by_ slice} {
    set fromDate [clock scan $dat1]
    set toDate   [clock scan $dat2]

    if {$slice eq "day"} then {set incrementor [expr 24 * 60]}
    if {$slice eq "hour"} then {set incrementor 60}

    set method DateRange

    puts "Scanning from [clock format $fromDate -format "%c"] to [clock format $toDate -format "%c"] by $slice"
    for {set dateCursor $fromDate} {$dateCursor <= $toDate} {set dateCursor [clock add $dateCursor $incrementor minutes]} {
        # ...
    }
}
process_range for "client" from "2013-10-18 00:00" to "2013-10-20 23:59" by day
</code>```

Are there any other languages that permit this kind of, almost COBOL-esque, syntax modification?

If you're wondering why I'm asking, it's for setting up stuff so that others with a not-as-geeky-as-I-am skillset can declare processing tasks.

Body:
There are many languages out there that are quite flexible. Many (often newer) languages pride themselves in their suitability for domain-specific languages (DSLs). However, some of your examples need some macro system.

Some languages that prominently use macros:

Lisp and descendants. These work as abstract syntax tree (AST) substitutions.

C, C++. The C preprocessor uses token-level subtitution, and is less powerful than Lisp macros. Your first example can be directly translated to C macros:

// untested
#define repeat for(;;) {
#define until(cond) if(cond) break; }

auto n = 1;
repeat {
  n++;
} until(n > 100)

Many languages allow functions to be called with keywords. Examples include

Lisps like Common Lisp.

Smalltalk and descendants.

Python:

Some languages have syntax that allow to fake named arguments, e.g.

many command-line interfaces:

git commit --file=foo.txt --message="Some fixes" --author=me

Any language with dictionary literals

Perl.

Javascript: foo.bar({ x: 42, y: somethingElse }).

Languages that have function literals/lambdas/closures don't need macros to define new control flow.

Any functional language, e.g. Lisps, ML

Smalltalk and descendants. Especially noteworthy is Ruby with its ubiquitous do ... end blocks.

With clumsy syntax: C++11, Perl, Javascript.

There are some languages that have a flexible view on operators, so that a lot of punctuation like parens for function calls etc. can be left out. An example would be Scala.


答:
It depends on what you want to write.

If all you want to write is a specific function that will be called from a "driver" program written in C, and if you do not need to perform a system call, then the C compiler you use is much more important than the architecture, because it prescribes how you have to expose your functions.

If you are instead interested in writing full fledged applications in assembly and making use of system calls — or writing device drivers — then the operating system is very relevant as well.

So basically, pick the one you want to write programs for.

In FreeBSD's developers handbook, there is a chapter devoted to assembly programming.  It is short and well written, and contains interesting examples, culminating with a simple CGI script(!).  You can read it to get a feeling:

http://www.freebsd.org/doc/en/books/developers-handbook/x86.html

P.S.: Assembly is one of the very first languages I learned in the middle of the nineties.  I learned it on an MS-DOS 6.22 system, using Isaacson's shareware assembler and Ralf Brown's interrupt list… thanks to Virtual Box you can probably get that feeling again! :-)

Title: Is there much difference between X86 Assembly language on Windows and Linux?

Body: I'm a complete beginner at Assembly, and my aim is to learn as much as I can to do with Assembly to one day I can reach expert level (I know I'm way off right now, but you never know). My only problem is this: I've got two books which both teach assembly, one on a Linux and the other on Windows. They are Jeff Duntemann's Assembly Language Step By Step (the linux one) and Introduction to 80x86 Assembly Language and Computer Architecture (the windows version). If I want to get the best out of assembly, should I do this on linux and windows? Also, is the syntax the same on Windows and Linux or will I have teach my self again when learning on the other OS( which is my main concern, I want to be able to use assembly on windows and linux).</p>


问:
Emacs-as-OS: obsolete?
In an attempt to reach at least beginner status with such a legendary editor, I have been coding in Emacs for the last two months.  I try to keep an open heart, but I find myself continally disagreeing with one core design choice: that Emacs allow its users to never have to leave.  In a 2010 world, I just think that every side feature of Emacs is hopelessly behind dedicated software:

I would never use its built-in browser; Chrome is years ahead.

I would never use its dired feature; Path Finder (Mac OS X) suits my needs.

I would never use its built-in email; the Gmail web interface has more relevant features like Priority Inbox.

Etc.

Sure, I might occasionally dip into Emacs to use regexps, etc. for one of the above tasks, but other than regexps, I really see no reason to ever touch those side features.  I'm a completely newbie, yet I have a strong gut feeling that Emacs-as-an-OS is obsolete.

Emacs experts, do you think that Emacs' choice to be a comprehensive environment is the right choice for 2010 and the future?  Are there particular peripheral features that are still at or ahead of their time compared to alternatives?

答:
Somewhere in my collection of stuff I'm sure my wife wishes I'd just throw away, I have a copy of Emacs on QIC-40 Tape. I paid $50 to get it.

I couldn't #@%#$#$%@^#%# stand it then, I can't stand it now. I'm not saying it isn't a great editor for some, but for me .. it just gets in the way more than anything. It's original inception was to work around coke bottle keys, and it did that very well.

If you run a program, any program, you do it in the hopes that it increases (or at least, doesn't hinder) your productivity. If it doesn't work for you, don't use it.

Trust me, you aren't the problem.

Title: Emacs-as-OS: obsolete?


答:
Assembly differs between platforms, and even between different assemblers on the same platform.  System calls and interrupts will be different, and there's the matter of AT&T vs. Intel syntax.  However, the difference between Windows and Linux assembly is much smaller than the difference between x86 and PIC assembly, for example.  If you know one, it's trivial to learn the other.

It's much more useful to be able to read assembly than to write it, and you get better at reading it by trying several different architectures.  Don't limit yourself.  In my job, x86 assembly never comes up, but I occasionally debug in PowerPC assembly.


答:
If you're signing in at github.companyname.com, then they've either set up a domain name for vanity purposes, or it's a GitHub Enterprise installation and not an organisation account on GitHub.com.

It it's the latter then the entire thing is using GitHub's software, but running on a server that companyname controls. Enterprise is provided as a fairly locked-down virtual machine, but the company's admins do have SSH Access, and they can dump all repositories as a single .tar file.

So, unless the user account they gave you also works at GitHub.com, I would have to assume that yes, the company's admin's could access the repository's data if they wanted to.


问:
Why C# is not statically typed but F# and Haskell are?
There was a talk given by Brian Hurt about advantages and disadvantages of static typing. Brian said that by static typing he don't mean C#, but F# and Haskell.

Is it because of dynamic keyword added to C#-4.0? But this feature is relatively rarely useful. By the way, there are ⊥ and unsafeCoerse in Haskell which obviously are not the same, but something that could blown your head off in runtime similarly like exception thrown as a result of dynamic.

Finally, why F# and Haskell could be named a statically typed languages and C# couldn't?

答:
There is lot of "marketing religion" and very few science here.

A static_typed laguage must support the definition of types and type checking at compile time, and a dynamic typed language must support the change of the type of the variable at runtime.

The two things are not necessarily mutually exclusive: a language can support both  the paradigms:

the only important thing is that what is defined to be static cannot become silently dynamic.


答:
Slightly paraphrased and shortened:

What I don't mean by static typing: C#. What I do mean: F#. Now with an actual solid definition …

That's not a definition, let alone a solid one. I think the answer to why C# isn't statically typed is, but F# is, is: Because the author of the talk said so.

A “definition” like that is completely useless, it doesn't say absolutely anything. And it's impossible to reach any conclusions based on that.

After watching the talk: it basically seems to be a praise of Haskell's type system.

Some of the points don't apply to the languages that supposedly have static typing (you can't easily implement STM in F#, because it's not pure). Some of the points do apply to the languages that “don't have” static typing (you don't have to worry about nulls much in modern C++; you can write type-safe Either in C#).

Title: Why C# is not statically typed but F# and Haskell are?

Body:
There was a talk given by Brian Hurt about advantages and disadvantages of static typing. Brian said that by static typing he don't mean C#, but F# and Haskell.

Is it because of dynamic keyword added to C#-4.0? But this feature is relatively rarely useful. By the way, there are ⊥ and unsafeCoerse in Haskell which obviously are not the same, but something that could blown your head off in runtime similarly like exception thrown as a result of dynamic.

Finally, why F# and Haskell could be named a statically typed languages and C# couldn't?


问:
deciphering columnar transposition cipher
I am looking for an idea on how to decipher a columnar transposition cipher without knowing the key or the length of the key.

When I take the cipher text as input to my algorithm I will guess the length of the key to be the factors of the length of the cipher text.

I will take the first factor suppose the length was 20 letters so I will take 2*10
(2 rows and 10 columns). Now I want to arrange the cipher text in the columns and read it row wise to see if there is any word forming and match it with a dictionary if it is something sensible. If it matches the dictionary then it means it is in correct order or else I want to know how to make other combinations of the columns and read the string again row wise.

Please suggest another approach that is more efficient.

答:
You have the correct general idea. But I want to point out that the message length doesn't have to be an exact multiple of the row count, e.g.

```<code>A B C  reordering  A C B
D E    --------->  D   E
</code>```

might become AD C BE. Accounting for this is rather difficult, as we don't know where the shorter columns are. Assuming we are partitioning into three columns, we might get A DC BE, AD C BE or AD CB E. The situation gets worse for a larger number of columns. One solution might be to initially decrypt everything but the last row, so that we know the order of columns. The uncertain characters can then be distributed over the leading columns.

As the columns may be re-ordered, we need a way to determine the original order. Unfortunately, there are r! different combinations. This is trivial for a small number of columns, where brute-forcing all combinations is a viable strategy. Otherwise, we have to employ an heuristic that guides us through all combinations.

One suitable heuristic considers letter transitions. We can build such a table from sufficiently large example data. Given a letter a and a letter b, we can then estimate the probability that a is followed by b in a text. Between two columns, we ususally have multiple transitions, so we can multiply the probability of each pair. Doing this for all columns produces an index we can sort by, and examine the column transition with the highest probability first. Note: This is a rather gross abuse of statistics, but it works out in this simple case where the probabilities are only used to decide one transition.

For example, assume we have the ciphertext eleatytoaryf_s_do_hwre_l, and we are just going to assume we have four columns. This gives us:

```<code>1234
et_h
losw
ea_r
arde
tyo_
yf_l
</code>```

It is irrelevant which column we pick first, so I am going to take #2. We now have probabilities for possible 2nd columns (frequency data obtained from an english dictionary file):

```<code>21 23 24
te t_ th
ol os ow
ae a_ ar
ra rd re
yt yo y_
fy f_ fl
 |  |  |                  raw   normalized
 |  |  `-1.6713389025628 e-06 = 0.9985
 |  `----1.10726823199948e-09 = 0.0007
 `-------1.39822078585934e-09 = 0.0008
</code>```

Just looking at the exponent, we can see that the 2→4 transition is the most probable. We repeat this for the next transition:

```<code>241 243
the th_
owl ows
are ar_
rea red
y_t y_o
fly fl_
  |   |                 raw   normalized
  |   `-1.9732647912631e-08 = 0.1122
  `-----1.5611637229838e-07 = 0.8878
</code>```

This declares the 4→1 transition most probable. Now only one column is left, so we get the transitions 2→4→1→3, which produces the cleartext the_owls_are_ready_to_fly. This looks like it is English, so we can stop here. If this weren't the case, we would backtrack to the last decision point, which was the 4→? transition. If choosing 4→3 had produced gibberish as well, backtracking to the previous decision point would have us examine 2→1, and then decide 1→?.

This heuristic may be optimized further. The problem can be expressed in graph theory as lazily sorting all paths through all vertices by their total weight in a directed, weighted graph where the vertices are columns, and the edges are transition probabilities, and the edge weights combine multiplicative. For calculating the transition probability we have to normalize the probabilities so that the weights of all outgoing edges add to 1.

Body:
You have the correct general idea. But I want to point out that the message length doesn't have to be an exact multiple of the row count, e.g.

A B C  reordering  A C B
D E    --------->  D   E

might become AD C BE. Accounting for this is rather difficult, as we don't know where the shorter columns are. Assuming we are partitioning into three columns, we might get A DC BE, AD C BE or AD CB E. The situation gets worse for a larger number of columns. One solution might be to initially decrypt everything but the last row, so that we know the order of columns. The uncertain characters can then be distributed over the leading columns.

As the columns may be re-ordered, we need a way to determine the original order. Unfortunately, there are r! different combinations. This is trivial for a small number of columns, where brute-forcing all combinations is a viable strategy. Otherwise, we have to employ an heuristic that guides us through all combinations.

One suitable heuristic considers letter transitions. We can build such a table from sufficiently large example data. Given a letter a and a letter b, we can then estimate the probability that a is followed by b in a text. Between two columns, we ususally have multiple transitions, so we can multiply the probability of each pair. Doing this for all columns produces an index we can sort by, and examine the column transition with the highest probability first. Note: This is a rather gross abuse of statistics, but it works out in this simple case where the probabilities are only used to decide one transition.

For example, assume we have the ciphertext eleatytoaryf_s_do_hwre_l, and we are just going to assume we have four columns. This gives us:

1234
et_h
losw
ea_r
arde
tyo_
yf_l

It is irrelevant which column we pick first, so I am going to take #2. We now have probabilities for possible 2nd columns (frequency data obtained from an english dictionary file):

21 23 24
te t_ th
ol os ow
ae a_ ar
ra rd re
yt yo y_
fy f_ fl
 |  |  |                  raw   normalized
 |  |  `-1.6713389025628 e-06 = 0.9985
 |  `----1.10726823199948e-09 = 0.0007
 `-------1.39822078585934e-09 = 0.0008

Just looking at the exponent, we can see that the 2→4 transition is the most probable. We repeat this for the next transition:

241 243
the th_
owl ows
are ar_
rea red
y_t y_o
fly fl_
  |   |                 raw   normalized
  |   `-1.9732647912631e-08 = 0.1122
  `-----1.5611637229838e-07 = 0.8878

This declares the 4→1 transition most probable. Now only one column is left, so we get the transitions 2→4→1→3, which produces the cleartext the_owls_are_ready_to_fly. This looks like it is English, so we can stop here. If this weren't the case, we would backtrack to the last decision point, which was the 4→? transition. If choosing 4→3 had produced gibberish as well, backtracking to the previous decision point would have us examine 2→1, and then decide 1→?.

This heuristic may be optimized further. The problem can be expressed in graph theory as lazily sorting all paths through all vertices by their total weight in a directed, weighted graph where the vertices are columns, and the edges are transition probabilities, and the edge weights combine multiplicative. For calculating the transition probability we have to normalize the probabilities so that the weights of all outgoing edges add to 1.


答:
The major problem with third party libraries, is that you need to retest YOUR application when you update them, before it can go in production.  So unless you have a reported bug, which require updating a library, you don't touch them until you have the time to do a complete quality assurance cycle.

This is usually done when releasing a new version.

I would, however, suggest that you have a test suite in place for continuous build that allow you to update the libraries in the development branch and do so automatically.  This will ensure that you discover early when it breaks, so you can file bugreports to the project.

Title: How to keep your third party libraries up to date?

Body:
Let's say that I have a project that depends on 10 libraries, and within my project's trunk I'm free to use any versions of those libraries. So I start with the most recent versions. Then,  each of those libraries gets an update once a month (on average). Now, keeping my trunk completely up to date would require updating a library reference every three days.

This is obviously too much. Even though usually version 1.2.3 is a drop-in replacement for version 1.2.2, you never know without testing. Unit tests aren't enough; if it's a DB / file engine, you have to ensure that it works properly with files that were created with older versions, and maybe vice versa. If it has something to do with GUI, you have to visually inspect everything. And so on.

How do you handle this? Some possible approaches:

If it ain't broke, don't fix it. Stay with your current version of the library as long as you don't notice anything wrong with it when used in your application, no matter how often the library vendor publishes updates. Small incremental changes are just waste.

Update frequently in order to keep change small. Since you'll have to update some day in any case, it's better to update often so that you notice any problems early when they're easy to fix, instead of jumping over several versions and letting potential problems to accumulate.

Something in between. Is there a sweet spot?


答:
I'm addressing the overlap between Haskell and
F#'s type systems. The part they share is a simplified subset of a system known sometimes as System F. F# by necessity provides bits and pieces of C#'s type system, but this isn't what the speaker was talking about.

Both C# and Haskell/F# are statically typed, but they're two different flavors.

Subtyping

Specifically, C# is a statically typed language with subtyping. This means that if you look at the typing rules for C# there's one like

```<code> Env |- x : T, T' <: T
 ---------------------
     Env |- x : T'
</code>```

Which means that any well typed term has more than one potential type. This in not the case in (vanilla) Haskell or F#. Every type has a single most general type, a principal type. This has a few benefits like total type inference.

Expressions Everywhere

Besides this, Haskell and F# have a greater emphasis on expressions, expressions have types, but statements don't. This means that in C#, the compiler is checking less of your code, because less of your code has types. In Haskell, everything has a real, checkable type.

In substantive terms, every single node on a Haskell AST has a type or kind (or sort). The same cannot be said of a C# one.

Sum Types

Beyond this, Haskell and F# have what are known as sum types.

```<code>data Bool = True | False
</code>```

This is how a boolean is defined in Haskell. This provides a few different guarantees than in C#. For example, when there are a discrete number of things in C#, like say, an AST. We can model this with an inheritance hierarchy, but these are open. Anyone can come along and add something to it. We can use an Enum, but then there's no sane way to attach data to each tag uniformly. This is what's called a tagged union, and it's up to you to implement/use it correctly, the compiler ain't gonna help.

This makes it very hard to ensure that we've covered all possible nodes of an AST. For example, say you have a function

```<code>doStuff :: AST -> AST
doStuff (SomeExpr ..) = ...
doStuff (SomeStatement ..) = ...
--// doStuff (SomeIf ...) = Oh noes, we forgot a node
</code>```

The compiler can warn you because it can prove exactly how many nodes there are, ever. In C#, the equivalent would have to be done with downcasting, and then, since the set of nodes in our hierarchy is open, there's no way to issue compile time warnings.

A company, Jane Street, raves about how useful this feature is in their large OCaml code base. Watch a few of their talks, they talk quite a bit about how using OCaml impacts them in the Real World.

Soapbox

Now I've outlined quite a few differences over System F over many mainstream type systems, but they're all still static type systems. It does bother me when people call Java/C#/C++ "not statically typed" they are. And they certainly give you more compile time guarantees than say, Python. So it's a bit unfair to dismiss them out right.

Body:
I'm addressing the overlap between Haskell and
F#'s type systems. The part they share is a simplified subset of a system known sometimes as System F. F# by necessity provides bits and pieces of C#'s type system, but this isn't what the speaker was talking about.

Both C# and Haskell/F# are statically typed, but they're two different flavors.

Subtyping

Specifically, C# is a statically typed language with subtyping. This means that if you look at the typing rules for C# there's one like

 Env |- x : T, T' <: T
 ---------------------
     Env |- x : T'

Which means that any well typed term has more than one potential type. This in not the case in (vanilla) Haskell or F#. Every type has a single most general type, a principal type. This has a few benefits like total type inference.

Expressions Everywhere

Besides this, Haskell and F# have a greater emphasis on expressions, expressions have types, but statements don't. This means that in C#, the compiler is checking less of your code, because less of your code has types. In Haskell, everything has a real, checkable type.

In substantive terms, every single node on a Haskell AST has a type or kind (or sort). The same cannot be said of a C# one.

Sum Types

Beyond this, Haskell and F# have what are known as sum types.

data Bool = True | False

This is how a boolean is defined in Haskell. This provides a few different guarantees than in C#. For example, when there are a discrete number of things in C#, like say, an AST. We can model this with an inheritance hierarchy, but these are open. Anyone can come along and add something to it. We can use an Enum, but then there's no sane way to attach data to each tag uniformly. This is what's called a tagged union, and it's up to you to implement/use it correctly, the compiler ain't gonna help.

This makes it very hard to ensure that we've covered all possible nodes of an AST. For example, say you have a function

doStuff :: AST -> AST
doStuff (SomeExpr ..) = ...
doStuff (SomeStatement ..) = ...
--// doStuff (SomeIf ...) = Oh noes, we forgot a node

The compiler can warn you because it can prove exactly how many nodes there are, ever. In C#, the equivalent would have to be done with downcasting, and then, since the set of nodes in our hierarchy is open, there's no way to issue compile time warnings.

A company, Jane Street, raves about how useful this feature is in their large OCaml code base. Watch a few of their talks, they talk quite a bit about how using OCaml impacts them in the Real World.

Soapbox

Now I've outlined quite a few differences over System F over many mainstream type systems, but they're all still static type systems. It does bother me when people call Java/C#/C++ "not statically typed" they are. And they certainly give you more compile time guarantees than say, Python. So it's a bit unfair to dismiss them out right.


问:
Authenticating users for a website
I'm working on a website and I want to validate that an individual is an employee at one of a large number of companies (probably using their company's email address, which I don't know before hand). The idea being some users are the general public and others are from these companies. And I need some way to authenticate that the users claiming to be employees are being honest while still having a friendly enough UI.

I did an informal survey of people I know and the domains and emails will match in a majority of cases but they might not always match exactly so you might have a company with a website foo.com and an email billy@foobar.com (although foobar.com did redirect back to foo.com).

And while I can easily check that I'm not sure what other variations might be out there (maybe fooLA.com and email billy@foolosangeles.com, etc.)

答:
You require a moderation procedure there. You need to work out a user-friendly moderation procedure that may not offend the user claiming to be an employee of a certain company. The best and most credible way to determine is to contact the HR department of that company. </p>

<p>Verifying emails will not be a very credible way to determine whether a certain user is an employee or not. I would rather be sending an email to the registered user claiming to be an employee stating that your application is being moderated and we shall get back to you shortly once moderation is completed.     </p>

Title: Authenticating users for a website

Body:
You require a moderation procedure there. You need to work out a user-friendly moderation procedure that may not offend the user claiming to be an employee of a certain company. The best and most credible way to determine is to contact the HR department of that company.

Verifying emails will not be a very credible way to determine whether a certain user is an employee or not. I would rather be sending an email to the registered user claiming to be an employee stating that your application is being moderated and we shall get back to you shortly once moderation is completed.


问:
How to cut the line between quality and time?
On one hand, I have been taught by various software engineering books ([1] as example) that my job as a programmer is to make the best possible software: great design, flexibility, to be easily maintained etc.

One the other hand although I realize that I actually write software for money and not for entertainment, although is very nice to write good code and plan ahead and refactor after writing and ... I wonder if it is always best for the business (after all we should be responsible). Is the business always benefiting from a best code? Maybe I'm over-engineering something, and it's not always useful?

So how should I know when to stop in the process to achieving the best possible code? I am sure that experience is something that makes a difference here, but I believe this cannot be the only answer.

[1] Uncle Bob's in Clean Code says at page 6 about the fact that:

They [managers] may defend the schedule and requirements with passion; but that’s their job. It’s your job to defend the code with equal passion.

答:
There is no line between quality and time. There's the Project Management Triangle:

Quality is a function of those other factors - time, cost, and scope. It doesn't matter what you want the quality to be, if you're dealing with fixed-cost/fixed-scope and have a reduction in available time, then quality diminishes as a result.

Perhaps what you are talking about is the "definition of done" used by a lot of different methodologies (especially Agile ones). That is up to your business and technology team to agree on. For example, on our team it means 80% unit test coverage, 80% acceptance test feature coverage, all content approved and translated by marketing teams, and any regression bugs either fixed or downgraded by the product manager. There are a few other things but you get the idea.

There's never going to be any bar for "code quality" because it means different things to different people. Pair programming and code review are useful tools for keeping the code quality reasonably high - if other people on your team can understand and maintain it without feeling sick to their stomachs, it's probably good enough.

If you want to institute metrics like checkstyle or FXCop, dependency analysis, code coverage, CRAP, etc., that's up to you and your team, you can make it part of your definition of done if you want. Your business owners will probably want to understand the value of these various things to you, why you consider them important and why they need to be done before a feature is releasable. If you can't justify it, don't do it.


问:
Test Doubles : Do they go in "source packages" or "test packages"?
I've got a couple of data access objects (DefaultPersonServices.class, DefaultAddressServices.class) which is responsible for various CRUD operations in a database.

A few different classes use these services, but as the services requires that a connection is established with a database I can't really use them in unit tests as they take too long. Thus, I'd like to create a test doubles for them and simply do FakePersonServices.class and FakeAddressService.class implementations which I can use throughout testing.

Now, this is all good (I assume)...but my question relates to where I put the test doubles. Should I keep them along with the default implementations (aka "real" implementations) or should I keep them in a corresponding test package.

The default implementations are found in Source Packages : com.company.data.services. Should I keep the test doubles here too, or should the test doubles rather be in Test Packages : com.company.data.services?

答:
Unless they will actually be used by something other than tests, then they belong in the test package.

Possibly you might want them to go into a separate "test objects" package if you're publishing your "source packages" and want other people to be able to write unit tests incorporating them, but unless you know this to be the case right now, I'd say YAGNI.

FWIW: There is only one instance in my past where I actually included fakes in the primary source code, and that was when the site was actually designed to be able to run in "demo mode" without an underlying database. As you can probably guess, these were true fakes, not just stubs or dummies, and the maintenance on them was considerable. Very few projects have any need for this, but I'm pointing it out anyway for the sake of completeness.


答: Bob Martin is talking about the tension between parties with conflicting goals,.  He is suggesting that it is your responsibility as Speaker for the Code to advocate for it and for increasing its quality.  He assumes that there are others who will advocate for the business's need or desire to weight other items (e.g., deadlines) higher than you will.  When the tension between the desires of all the parties are in balance, the result will be optimum for the business.  When any one party's desire is too strong or too weak, the result will be sub-optimum.  As programmers, we can deliver perfect code, but in doing so, we may cause our business to miss its market timing and leave everyone in the company unemployed.  Managers may achieve deadlines perfectly, but in doing so, they may deny us the time and resources we need to produce code of acceptable quality, leading to the same result.

Title: How to cut the line between quality and time?

Body:
On one hand, I have been taught by various software engineering books ([1] as example) that my job as a programmer is to make the best possible software: great design, flexibility, to be easily maintained etc.

One the other hand although I realize that I actually write software for money and not for entertainment, although is very nice to write good code and plan ahead and refactor after writing and ... I wonder if it is always best for the business (after all we should be responsible). Is the business always benefiting from a best code? Maybe I'm over-engineering something, and it's not always useful?

So how should I know when to stop in the process to achieving the best possible code? I am sure that experience is something that makes a difference here, but I believe this cannot be the only answer.

[1] Uncle Bob's in Clean Code says at page 6 about the fact that:

They [managers] may defend the schedule and requirements with passion; but that’s their job. It’s your job to defend the code with equal passion.


答:
So how should I know when to stop in the process to achieving the best possible code? I am sure that experience is something that makes a difference here, but I believe this cannot be the only answer.

You do not need to achieve the best possible code but to write a code that is in the process of becoming the best possible and offers the least possible resistance when you push it in this direction.

When you design your program, you can check the design's quality by considering likely scenarios for the future evolution of your program's functionality and figure out how hard or how easy these developments would be in relation with the design you made.

EDIT — (A response to @Aaronaught, which is too long for a comment.) I did not mean that considering likley scenarios are the only criterium for checking robustness of a design.  Of course, use cases and requirements must be fulfilled, before checking anything else. But if you consider only them, then there is a crystal clear cut between quality and time.

The best possible program is internationalised, can recover gently from errors or provide detailed diagnostics, uses a not so old GUI toolkit (if the customer cares), has a featureful data explorer that will help to spot errors in the input and so on. But while we do not need to build everything in from the beginning, it can be useful to take provisions so that these foreseeable additions can be easily made.


问:
Writing the minimum code to pass a unit test - without cheating!
When doing TDD and writing a unit test, how does one resist the urge to "cheat" when writing the first iteration of "implementation" code that you're testing?

For example:

Let's I need to calculate the Factorial of a number.  I start with a unit test (using MSTest) something like:

```<code>[TestClass]
public class CalculateFactorialTests
{
    [TestMethod]
    public void CalculateFactorial_5_input_returns_120()
    {
        // Arrange
        var myMath = new MyMath();
        // Act
        long output = myMath.CalculateFactorial(5);
        // Assert
        Assert.AreEqual(120, output);
    }
}
</code>```

I run this code, and it fails since the CalculateFactorial method doesn't even exist.  So, I now write the first iteration of the code to implement the method under test, writing the minimum code required to pass the test.

The thing is, I'm continually tempted to write the following:

```<code>public class MyMath
{
    public long CalculateFactorial(long input)
    {
        return 120;
    }
}
</code>```

This is, technically, correct in that it really is the minimum code required to make that specific test pass (go green), although it's clearly a "cheat" since it really doesn't even attempt to perform the function of calculating a factorial.  Of course, now the refactoring part becomes an exercise in "writing the correct functionality" rather than a true refactoring of the implementation.  Obviously, adding additional tests with different parameters will fail and force a refactoring, but you have to start with that one test.

So, my question is, how do you get that balance between "writing the minimum code to pass the test" whilst still keeping it functional and in the spirit of what you're actually trying to achieve?

答:
I do 100% agree with Robert Harveys suggestion here, it's not just about making tests pass, you need to keep the overall goal in mind too.

As a solution to your painpoint of "it's only verified to work with a given set of inputs" I'd propose using data driven tests, such as xunit theory. The power behind this concept is that it allows you to easily create Specifications of inputs to outputs.

For Factorials, a test would look like this:

```<code>    [Theory]
    [InlineData(0, 1)]
    [InlineData( 1, 1 )]
    [InlineData( 2, 2 )]
    [InlineData( 3, 6 )]
    [InlineData( 4, 24 )]
    public void Test_Factorial(int input, int expected)
    {
        int result = Factorial( input );
        Assert.Equal( result, expected);
    }
</code>```

You could even implement a test-data provide (that returns IEnumerable<Tuple<xxx>>) and encode a mathematic invariant, such as repeatedly dividing by n will yield n-1).

I find this tp be a very powerful way of testing.

Body:
I do 100% agree with Robert Harveys suggestion here, it's not just about making tests pass, you need to keep the overall goal in mind too.

As a solution to your painpoint of "it's only verified to work with a given set of inputs" I'd propose using data driven tests, such as xunit theory. The power behind this concept is that it allows you to easily create Specifications of inputs to outputs.

For Factorials, a test would look like this:

    [Theory]
    [InlineData(0, 1)]
    [InlineData( 1, 1 )]
    [InlineData( 2, 2 )]
    [InlineData( 3, 6 )]
    [InlineData( 4, 24 )]
    public void Test_Factorial(int input, int expected)
    {
        int result = Factorial( input );
        Assert.Equal( result, expected);
    }

You could even implement a test-data provide (that returns IEnumerable<Tuple<xxx>>) and encode a mathematic invariant, such as repeatedly dividing by n will yield n-1).

I find this tp be a very powerful way of testing.


问:
Simple task framework - building software from reusable pieces
I'm writing a web service with several APIs, and they will be sharing some of the implementation code. In order not to copy-paste, I would like to ideally implement each API call as a series of tasks, which are executed in a sequence determined by the business logic.

One obvious question is whether that's the best strategy for code reuse, or whether I can look at it in a different way. But assuming I want to go with tasks, several issues arise:

What's a good task interface to use?

How do I pass data computed in one task to another task in the sequence that might need it?

In the past, I've worked with task interfaces like:

```<code>interface Task<T, U> {
    U execute(T input);
}
</code>```

Then I also had sort of a "task context" object which had getters and setters for any kind of data my tasks needed to produce or consume, and it gets passed to all tasks. I'm aware that this suffers from a host of problems. So I wanted to figure out a better way to implement it this time around.

My current idea is to have a TaskContext object which is a type-safe heterogeneous container (as described in Effective Java). Each task can ask for an item from this container (task input), or add an item to the container (task output). That way, tasks don't need to know about each other directly, and I don't have to write a class with dozens of methods for each data item. There are, however, several drawbacks:

Each item in this TaskContext container should be a complex type that wraps around the actual item data. If task A uses a String for some purpose, and task B uses a String for something entirely different, then just storing a mapping between String.class and some object doesn't work for both tasks. The other reason is that I can't use that kind of container for generic collections directly, so they need to be wrapped in another object.

This means that, based on how many tasks I define, I would need to also define a number of classes for the task items that may be consumed or produced, which may lead to code bloat and duplication. For instance, if a task takes some Long value as input and produces another Long value as output, I would have to have two classes that simply wrap around a Long, which IMO can spiral out of control pretty quickly as the codebase evolves.

I briefly looked at workflow engine libraries, but they kind of seem like a heavy hammer for this particular nail. How would you go about writing a simple task framework with the following requirements:

Tasks should be as self-contained as possible, so they can be composed in different ways to create different workflows.

That being said, some tasks may perform expensive computations that are prerequisites for other tasks. We want to have a way of storing the results of intermediate computations done by tasks so that other tasks can use those results for free.

The task framework should be light, i.e. growing the code doesn't involve introducing many new types just to plug into the framework.

答:
You need to make a generic wrapper for the TaskContext contents. As Thulasi says, use someone else's wrapper for this. JSON, XML, temp files if you have to, even a proper database, whatever. If you want to keep things light code reuse is the way to go.

Once you have a task coordinator and a bunch of tasks running you'll no doubt want some kind of communication (stop, now!), then the common data store will grow and you'll need to limit it, caching will become more important... and you'll have your very own framework. I suggest having a very clear idea of exactly how far you're willing to go down that path before you cut over to an existing "heavy" framework.

My suggestion is that you limit yourself at 'no communication'. If you only have fire-and-forget tasks that run quickly and can be killed harmlessly (ie, your data store is transactional) the problem is pretty tractable. Anything more than that and you are better off dealing with the frameworks. There's no reason you can't keep the framework involvement minimal if your requirements are simple.


问:
Attaching Events to Document Better Than Attaching Them to Elements?
While bouncing around StackOverflow, I've noticed a number of people attaching events (notably click events) to the document as opposed to the elements themselves.

Example:

Given this:

```<code><button id="myButton">CLICK ME</button>
</code>```

Instead of writing this (using jQuery just for brevity):

```<code>$('#myButton').on('click', function() { ... });
</code>```

They do this:

```<code>$(document).on('click', function() { ... });
</code>```

And then presumably use event.target to drill down to the element that was actually clicked.

Are there any gains/advantages in capturing events at the document level instead of at the element level?

答:
Maybe (and that's a big maybe) in some (again, a big some) cases that could (and a big could) increase performance of the app, though I can't say why.

What it definitely does is make the code harder to read, since you'd have to go into the callback to find out what element the event is really attaching too; and also potentially violates the DRY principle, since you can't reuse the callback in another element event. You can certainly add another clause to your event.target if statement, but that would obfuscate the code even further.

Which brings me back to my first statement, somebody must have thought he could increase performance of the app, since the only reason for obfuscating code that makes sense, is improving performance. Sadly, most people tend to attack performance issues where they think the issue is, as opposed to profiling the code and determining exactly what is underperforming.

Again, I'm not sure that this would improve performance, but I'm quite sure it needlessly obfuscates your code, and that is in itself bad, especially a couple of months after you started writing it and come back to modify it. The code will likely now have multiple events bound to document with multiple ifs (some with one clause and some with n clauses) to check when trying to debug an event.

just my 2 cents

Edit: I really can't come up with a situation where binding an event to the document would make it perform better. Perhaps the code you've seen requires capturing a click anywhere in the document and executing the same code regardless of where the click originates from? it's the only reason I find could justify doing such a thing


答:
There is one advantage:  If #myButton isn't always on the page (that is, it's inserted through AJAX or altering innerHTML or the DOM directly), then there's no need to recreate the event listener over and over.

That said, you shouldn't do it due to both performance and obfuscation.  If this is happening on your page, at least put the event on a containing element that is always there - #content or #menu or something similar.

And even then, to address the example code in your question, jQuery in particular has syntax to do that without manual checking:

```<code>$(document).on('click', '#myButton', function() { ... });
</code>```

Although, as I said above, it is better to restrict the event to where it can appear:

```<code>$('#commentBox').on('click', '#myButton', function() { ... });
</code>```

Title: Attaching Events to Document Better Than Attaching Them to Elements?

Body:
While bouncing around StackOverflow, I've noticed a number of people attaching events (notably click events) to the document as opposed to the elements themselves.

Example:

Given this:

```<code><button id="myButton">CLICK ME</button>
</code>```

Instead of writing this (using jQuery just for brevity):

```<code>$('#myButton').on('click', function() { ... });
</code>```

They do this:

```<code>$(document).on('click', function() { ... });
</code>```

And then presumably use event.target to drill down to the element that was actually clicked.

Are there any gains/advantages in capturing events at the document level instead of at the element level?

Body:
There is one advantage:  If #myButton isn't always on the page (that is, it's inserted through AJAX or altering innerHTML or the DOM directly), then there's no need to recreate the event listener over and over.

That said, you shouldn't do it due to both performance and obfuscation.  If this is happening on your page, at least put the event on a containing element that is always there - #content or #menu or something similar.

And even then, to address the example code in your question, jQuery in particular has syntax to do that without manual checking:

$(document).on('click', '#myButton', function() { ... });

Although, as I said above, it is better to restrict the event to where it can appear:

$('#commentBox').on('click', '#myButton', function() { ... });


问:
Can anyone explain representation of float in memory?
Can anyone help me in understanding how float values are stored in the memory.

My doubt is here float values contain '.' (for example 3.45) how the '.' will be represented in the memory?

Can anyone please clarify me with a diagram?

答:
The . is not stored at all. First, you should understand engineering notation, which has a fixed-precision factor and an integer exponent: 1 is 1.0 · 100 = 1.0E0, 2 is 2.0E0, 10 is 1.0E1 etc. This allows for very short notation of large numbers. One billion is 1.0E9. The factor before the E is usually notated as a fixed-precision number: 1.00000E9. A result from this is that the number one billion and one = 1,000,000,001 and one billion are both the same in this notation, when the precision isn't large enough. Also note that the factor never needs a leading zero. Instead, the exponent can be decremented until that is no longer the case.

In memory, a floating point number is represented similarly: One bit has the sign, some bits form the factor as a fixed-precision number (“mantissa”), the remaining bits form the exponent. Significant differences to base-10 engineering notation is that of course now the exponent has base 2. The exact size of each part depends on the exact floating-point standard you are using.

ContentLicense: CC BY-SA 4.0


答:
I would think about updating all the libraries of a project right before or just after a release. This however could get out of hand if you rely on more than 10 or 15 libraries, in which case some kind of update checking mechanism would help out greatly. The advantage of this is that you have a time dedicated to testing your libraries and can fix any issues in one pass. You also don't have to constantly keep track of updates from every single library, you just check on a certain day for any updates. </p>

<p>I would also go against any kind of auto updating feature in even a dev branch. It would be frustrating if in the middle of me working on something the project broke because a library auto updated itself, or I all of a sudden got Depreciation warnings for using an API that just got superseded by something else. </p>

Body:
I would think about updating all the libraries of a project right before or just after a release. This however could get out of hand if you rely on more than 10 or 15 libraries, in which case some kind of update checking mechanism would help out greatly. The advantage of this is that you have a time dedicated to testing your libraries and can fix any issues in one pass. You also don't have to constantly keep track of updates from every single library, you just check on a certain day for any updates.

I would also go against any kind of auto updating feature in even a dev branch. It would be frustrating if in the middle of me working on something the project broke because a library auto updated itself, or I all of a sudden got Depreciation warnings for using an API that just got superseded by something else.


问:
Requring static class setter to be called before constructor, bad design?
I have a class, say Foo, and every instance of Foo will need and contain the same List object, myList.

Since every class instance will share the same List Object, I thought it would be good to make myList static and use a static function to set myList before the constructor is called.

I was wondering if this was bad, because this requires the setter to be called before the constructor? If the person doesn't, the program will crash. Alternative way would be passing myList every time.

答:
Requiring a certain method to be called before another is called Sequential Coupling, and is often considered to be an antipattern. Take for example this code generator:

```<code>cg.enterScope();
... // add operations inside this scope
cg.leaveScope();
</code>```

Here, leaveScope always has to be called after enterScope, else incorrect code is emitted. This can be trivially refactored to use a Scope type:

```<code>Scope(scoped_operations).generate_code(cg);
</code>```

Your case is trickier, as you want to lazily initialize a static member before any instances of that class are created. I guess this will look like

```<code>TheClass.initialize();
var instance = new TheClass();  // first use
</code>```

The first step is to make initialize threadsafe. Then, it has to record whether it has already run. If so, any future calls simply short circuit:

```<code>static bool is_initialized = false;

static synchronized void initialize() {
  if (is_initialized) return;
  ...; // normal initialization
  is_initialized = true;
}
</code>```

Now we can do this call inside the constructor to make sure the class is always initialized before other code runs:

```<code>TheClass(...) {
  if (!is_initialized) initialize(); // try to avoid call to synchronized method
  ...;
}
</code>```

If the initialization doesn't have to happen lazily, various simpler solutions can be used. (In this context, lazy initialization means that initialization is only ever performed if an instance is created). For something as cheap as creating a List object, you will probably want to initialize it regardless of any objects created. Different languages have different mechanisms, e.g.

```<code>// Java, C#
static List<Foo> myList = new List<Foo>();

// Java: static initializer block
static {
  myList = new List<Foo>();
}
</code>```

If the initialization value is not known at compile time, but is rather provided by a user, this gets complicated again. In some languages you can parameterize classes themselves, e.g. TheClass = new TheMetaClass(42); instance = new TheClass(). In languages lacking a Metaobject Protocol, the Factory Pattern can be used instead: factory = new TheClassFactory(42); instance = factory.create(). This looks similar to the sequentially coupled example at the beginning, but with a factory the type system can guarantee that initialization has happened before an instance is created.

Body:
Requiring a certain method to be called before another is called Sequential Coupling, and is often considered to be an antipattern. Take for example this code generator:

cg.enterScope();
... // add operations inside this scope
cg.leaveScope();

Here, leaveScope always has to be called after enterScope, else incorrect code is emitted. This can be trivially refactored to use a Scope type:

Scope(scoped_operations).generate_code(cg);

Your case is trickier, as you want to lazily initialize a static member before any instances of that class are created. I guess this will look like

TheClass.initialize();
var instance = new TheClass();  // first use

The first step is to make initialize threadsafe. Then, it has to record whether it has already run. If so, any future calls simply short circuit:

static bool is_initialized = false;

static synchronized void initialize() {
  if (is_initialized) return;
  ...; // normal initialization
  is_initialized = true;
}

Now we can do this call inside the constructor to make sure the class is always initialized before other code runs:

TheClass(...) {
  if (!is_initialized) initialize(); // try to avoid call to synchronized method
  ...;
}

If the initialization doesn't have to happen lazily, various simpler solutions can be used. (In this context, lazy initialization means that initialization is only ever performed if an instance is created). For something as cheap as creating a List object, you will probably want to initialize it regardless of any objects created. Different languages have different mechanisms, e.g.

// Java, C#
static List<Foo> myList = new List<Foo>();

// Java: static initializer block
static {
  myList = new List<Foo>();
}

If the initialization value is not known at compile time, but is rather provided by a user, this gets complicated again. In some languages you can parameterize classes themselves, e.g. TheClass = new TheMetaClass(42); instance = new TheClass(). In languages lacking a Metaobject Protocol, the Factory Pattern can be used instead: factory = new TheClassFactory(42); instance = factory.create(). This looks similar to the sequentially coupled example at the beginning, but with a factory the type system can guarantee that initialization has happened before an instance is created.


答:
You have to ask, what do you really want out of the update? Most security fixes are actually trivial patches, in the form of fixing:

Off by one errors where arbitrary code can be copied to an unused space in a buffer

Dangling pointers, or something else that triggers undefined but (rather) deterministic behavior

Bugs that permit some kind of DoS

Bugs that accidentally make snooping of private data easy

Math blunders

Maintainers touching stuff they shouldn't (Debian SSL bug, anyone?)

If you look over most CVE's in the last five years, the patches that fix them are typically quite trivial, if you are using open libraries, which I hope you are.

Then you have actual bug fixes, which you probably want, but perhaps you already fixed it yourself. If it isn't broken, don't fix it.

Finally, you have new features .. and perhaps deprecated features. You need to examine those release notes and diffs carefully. Can you use them, even if they break an API that lots of other stuff depends on? If yes, it is time for surgery .. if no, cherry pick what you want and move on.

Some may disagree with me, but I refuse to use a library without source code.


问:
Is implementing an interface defined in a subpackage an anti-pattern?
Let's say I have the following:

```<code>package me.my.pkg;
public interface Something {
    /* ... couple of methods go here ... */
}
</code>```

and:

```<code>package me.my;
import me.my.pkg.Something;
public class SomeClass implements Something {
    /* ... implementation of Something goes here ... */
    /* ... some more method implementations go here too ... */
}
</code>```

That is, the class implementing an interface lives closer to the package hierarchy root than does the interface it implements but they both belong in the same package hierarchy.

The reason for this in the particular case I have in mind is that there is a previously-existing package that groups functionality which the Something interface logically belongs to, and the logical (as in both "the one you'd expect" and "the one where it needs to go given the current architecture") implementation class exists previously and lives one level "up" from the logical placement of the interface. The implementing class does not logically belong anywhere under me.my.pkg.

In my particular case, the class in question implements several interfaces, but that feels like it doesn't make any (or at least no significant) difference here.

I can't decide if this is an acceptable pattern or not. Is it or is it not, and why?

答:
Yes, it's acceptable, as long as the class and the interface are both definitely in the correct packages.

Organising classes into a hierarchical set of packages is a bit like organising classes into an inheritance hierarchy. It works pretty well most of the time, but there are plenty of legitimate cases which just don't fit.

Note that Java doesn't really even have a package hierarchy - the hierarchical nature doesn't extend further than the folder structure. I can't speak for the Java language designers, but I doubt they made this decision by accident!

I sometimes find it helps to think of the 'package hierarchy' as an aide to help programmers find the package they're looking for.