问:
Making the server request with high priority
I need to connect to a server and do manipulation with respect to HTTP GET and POST for my application and the server is generally used to handle multiple users with heavy load and many users might be sending multiple request at any moment.

I have 3 questions here.

The server is configured with ASP.NET

I am using Java to do my HTTP POST and GET requests.

Is there any way available to make my request data to have more priority than others ?

Also, I read some article in internet and it is mentioned that using proxies will help in speed up the process and will give us high chance of getting the connection with the server.

Is that true ? If yes, why ?

Thanks in advance.

答:
When there is a single server entry point, web requests are generally served in a first-in-first-served manner.

If the system architect is aware that some requests should have higher priority than other requests, he may employ a Bulkhead Pattern (either temporarily for an expected traffic spike, or as part of the stable architecture), where a dedicated entry-point is added for that traffic, to be handled by dedicated resources (put in a different queue, run on a different CPU or machine).

For example, if all traffic goes to http://www.example.com/my_service, "privileged" clients will be instructed to use http://vip.example.com/my_service, where they will be handled by a dedicated server, which may run the same code as the normal server, or may run dedicated code.

A more elaborate option is to configure the load balancer to dispatch certain client IPs to a separate server, which takes the control completely out of the client's hands.

There is no standard way for some client to get priority on some server arbitrarily, mainly because if there was such a way, wouldn't all of the clients be implemented that way? Who wants less than premium service?


问:
Should a lexer un-escape strings?
Is it a lexer's job to undo any escaping done to a string literal? For example:

```<code>"Me: \"Hello World!\""
</code>```

Becomes:

```<code>Me: "Hello World!"
</code>```

Should this conversion be done inside the lexer? I am guessing it should, because it'd allow for a more abstract and modular design. You could add ways to represent strings and you won't have to update every component.

答:
If you are implementing something close to string literals in C, then yes. This is because at the level of the parser, you are only concerned about something being a string literal and not how they are implemented.

But if you have some additional requirement such as the double quotes appearing inside the string literal must be matched (i.e., "\"" is invalid). Then this can only be captured only using a context free grammar and can only be handled by a parser.

ContentLicense: CC BY-SA 3.0

Title: Should a lexer un-escape strings?


问:
Logging events for reporting purposes
Are there any design patterns or best practices around logging events for use in reporting and BI systems.

For example in a system which manages orders from a website, it would be beneficial if a customer support worker could type in an order number and see that it the order was placed  on a certain day, dispatched on a certain day and delivered on another.

I can see 2 ways around this. I have an order object which has the fields:

```<code>OrderDate
DespatchDate
DeliveryDate
</code>```

and populate them if they have happend otherwise they will be null

OR

log some sort of events like which are messages like:

```<code>Order Number - "12312312" - Ordered on '2014/01/01'
Order Number - "12312312" - Despatched on '2014/01/01'
</code>```

and add store the events in a database.

Are there any guidelines for this?
For example how does the work item history in TFS work?

答:
Robert made good points in his answer.

In addition, you might want to look at Audit Log as described by Martin Fowler here (and perhaps, more generally, Temporal Patterns). If you wanted to do more than just business activity monitoring / business reporting of these events, you might want to look at Event Sourcing. Fowler provides an introduction here.

You can use these terms to search for other opinions on the web.

Title: Logging events for reporting purposes


问:
Should duck typing affect naming conventions?
I'm a C++/C# developer and recently I've started to learn Python. I think I understand the concept of duck typing right now except for one thing.

When I'm coding in C++ or C# I sometimes create completely unrelated classes that have similar methods with similar signatures, for example: Create(), Open(), Close(), ProcessData(), etc. It's not a big deal in C++ or C# (unless you want to mess with C++ templates), but in languages with duck typing like Python this could cause a disaster. Consider the following example:

```<code>class DbTransaction:
    def rollback(self):
        pass

class SourceControlChangeset:
    def rollback(self):
        pass

def rollback_transaction(transaction):
    transaction.rollback()

transaction = DbTransaction()
changeset = SourceControlChangeset()
rollback_transaction(transaction)
rollback_transaction(changeset) # Oops!
</code>```

Maybe be example is a bit artificial, but I think this could happen pretty easily in a big project with many classes.

What should I do in this situation? I think that type checking is not "pythonic" so my only idea is to change naming convention for class methods like this:

```<code>class DbTransaction:
    def rollback_transaction(self):
        pass

class SourceControlChangeset:
    def rollback_changeset(self):
        pass
</code>```

Any ideas?

答:
The unfortunate side effect of Duck Typing is that sometimes it isn't a duck, even if it walks like a duck and quacks like a duck.  Duck Typing only works in limited areas of similarity.

Your example, however, is itself a problem.  You should never rollback_transaction(transaction), you should always transaction.rollback().  If you have a valid reason to wrap the behavior of a method, you should do it "objectally", not procedurally, by creating a wrapper object whose method wraps the inner object's method.


问:
Should POCO domain classes contain collections?
The question title is not good, but I couldn't think of a way to word it better.

I am used to develop using POCO classes in my projects, that is, domain objects contain absolutely no logic, only data.

I am wondering which is the best approach when dealing with class relationships - to put a collection inside the class or to request it later.

For example, consider we have an e-commerce application, that has Orders, and Items inside those Orders. So we could have (pseudo-code)

```<code>class Order
{
     int id;
     List<OrderItem> Items;
}

class OrderItem
{
     Product product;
     int quantity;
}
</code>```

And then use it (1)

```<code>var o = LoadOrder(id);
foreach (var i in o.Items) {
</code>```

...or we could do:

```<code>class Order
{
    int id;
}
</code>```

And use it this way: (2)

```<code>var odr = LoadOrder(id);
var itms = LoadItemsOfOrder(odr);
foreach (var i in itms) {
    .....
</code>```

The first way is more compact and more "OOP-ish", but the second way gives more control on how and when items are requested, e.g. what if now I need to request only the items that have quantity > 3 ? And what if I don't use the Items collection at all (e.g. to display only a list of orders) - I will be doing unnecessary queries to the database.

In my older, big projects I've gone with a hybrid approach - the domain classes are of the first flavor but there are various "load" methods, like "LoadOrder" and "LoadOrderWithItems" or "FillOrderObject".

Now I am working on a small, toy project, no customers and crazy deadlines and got time to think on these issues.

I tried searching the web but it is very hard to find a POCO answer not related to Entity Framework. (I am not working in .net this time, but would like to apply these concepts.)

Question: is there a method which is clearly better than the other, or both are valid and "it depends" on my project, if I am aiming for performance or for code clarity and maintainability?.

答:
From the TDD point of view I would prefer pocos with collections over having specialalized LoadSubItems methods because it is much easier to create a testOrder with one orderitem
than to mock a databaseLoadMethod to implement a test for a order processing service.</p>


问:
Best practice for configuration files in a website
I am creating something similar to a Content Management System, that can be downloaded and used by everyone that needs it. I've been working in web-development for a couple of years (mainly as a hobby, i.e. creating personal homepages for acquaintances), but have never had the need of a user to enter his own configurations (let it be database connection, meta-data about his site, desired behaviour of the website).

Therefore I have no experience with custom configuration file handling. That's where my question lies: What is the best practice to handle custom website-wide configuration files and handle them in PHP?

I have thought of creating INI-files, that can be customized from within the admin panel and that are hidden to the user by .htaccess for security purposes. However I don't know if INI is the best method to do this considering that the page is being developed to be extensible through plugins (which may lead to another question soon).

So what is my best bet to handle configurability? For instance do I want to store database configuration in files somehow and have other configurations outsourced to the database itself? Or do I store everything in INI-files (also considering configurability for plugins: Should everyone of these have their own config-file)?

答:
The popular CMS like Wordpress stores its database configuration with few basic configuration options in php file called config.php and rest all in database.

This method is quite effective if you want to store single as well as multiple configurations which you may be thinking of like for theames, plugins, langualges etc.

Editing php config file with constants can also be also as user friendly as other text INI file if written so.

You will need to identify which settings can go in config file and other in database.


问:
If null is bad, why do modern languages implement it?
I'm sure designers of languages like Java or C# knew issues related to existence of null references (see Are null references really a bad thing?). Also implementing an option type isn't really much more complex than null references.

Why did they decide to include it anyway? I'm sure lack of null references would encourage (or even force) better quality code (especially better library design) both from language creators and users.

Is it simply because of conservatism - "other languages have it, we have to have it too..."?

答:
First of all, I think we can all agree that a concept of nullity is necessary. There are some situations where we need to represent the absence of information.

Allowing null references (and pointers) is only one implementation of this concept, and possibly the most popular although it is know to have issues: C, Java, Python, Ruby, PHP, JavaScript, ... all use a similar null.

Why ? Well, what's the alternative ?

In functional languages such as Haskell you have the Option or Maybe type; however those are built upon:

parametric types

algebraic data types

Now, did the original C, Java, Python, Ruby or PHP support either of those features ? No. Java's flawed generics are recent in the history of the language and I somehow doubt the others even implement them at all.

There you have it. null is easy, parametric algebraic data types are harder. People went for the simplest alternative.


问:
Do you actively think about security when coding?
When you're coding, do you actively think about your code might be exploited in ways it wasn't originally meant to do and thus gain access to protected information, run commands or something else you wouldn't want your users to do?</p>

答:
Yes.

I've dealt with enough hackers in the past to know that they're constantly trying to compromise any big site, and there are enough bots out there that even small sites aren't safe.

I try to think like a hacker all the time now, to the point where I sometimes worry my co-workers with casual comments on how systems we take for granted every day can be gamed.

ContentLicense: CC BY-SA 2.5


问:
Why is studying a Lisp interpreter in lisp so important?
I have seen many CS curriculums and learning suggestions for new programmers that call for the aspiring programmer to study a Lisp interpreter that is specifically written in Lisp.  All these sites say things similar to, "its an intellectual revelation", "it is an enlightenment experience every serious programmer should have," or "it shows you hardware/software relationships," and other vague statements, particularly from this article taken from this reputable how-to.

The general sentiment of my question is, how does Lisp achieve the above goals and why Lisp?  Why not some other language?

I am asking this because I just finished writing a scheme interpreter in scheme (taken from SICP http://mitpress.mit.edu/sicp/ ) and now I am writing a python interpreter in scheme and I am struggling to have this legendary epiphany that is supposed to come specifically from the former.  I am looking for specific technical details between the two languages that I can exploit in their scheme interpreters to gain understanding about how programs work.

More specifically:

Why is the study of an interpreter that is written in the language it interprets so emphasized - is it merely a great mental exercise to keep the original language and built language straight or are there specific problems whose solutions can only be found in the nature of the original language?

How do Lisp interpreters demonstrate good architecture concepts for one's future software design?

What would I miss if I did this exercise in a different language like C++ or Java?

What is the most used takeaway or "mental tool" from this exercise? **

** I selected the answer I did because I have noticed that I have gained from this exercise more skill in designing parsing tools in my head than any other single tool and I would like to find different methods of parsing that may work better for the scheme interpreter than the python interpreter.

答:
I'm not sure it is really important for everyone. You can be a successful developer without knowing how a Lisp interpreter works. When studying Computer Science, the basic ideas of Lisp should be learned though.

Lisp interpreters are important for Lisp programmers. They need to understand how an Interpreter ([and compiler]1) works, to fully understand how to use the language.

A Lisp interpreter is often used as a tool in computer science to teach students a few things:

understanding a compact and minimal language definition through an implementation: Alan Kay called it the Maxwell’s Equations of Software.

understanding language-level programming, by changing and extending the interpreter

understanding meta-level programming and the effects it has on the design and usage of a programming language. For example understanding what 'quoting' means and why it is necessary

understanding the interpretation of the programming language Lisp and its connection to the Lambda Calculus

As a teaching device, a Lisp interpreter is helpful, because it can be learned and understood in small time. Since few students already know about Lisp, the students are on a level field when it comes to learning above concepts.

ContentLicense: CC BY-SA 4.0


答:
It's never okay to satisfy hypothetical performance goblins at the expense of fewer lines of code or an API that more clearly expresses the relationship between entities. </p>

<p>So, the first example is preferred. Any decent ORM should be able to lazy-load the collection, and some of the more advanced ones will even let define a property on an entity with a custom loading function, also lazy-loaded. That takes care of both of your use cases without breaking encapsulation of the Order class and exposing its inner data structure. </p>

Title: Should POCO domain classes contain collections?

Body:
The question title is not good, but I couldn't think of a way to word it better.

I am used to develop using POCO classes in my projects, that is, domain objects contain absolutely no logic, only data.

I am wondering which is the best approach when dealing with class relationships - to put a collection inside the class or to request it later.

For example, consider we have an e-commerce application, that has Orders, and Items inside those Orders. So we could have (pseudo-code)

```<code>class Order
{
     int id;
     List<OrderItem> Items;
}

class OrderItem
{
     Product product;
     int quantity;
}
</code>```

And then use it (1)

```<code>var o = LoadOrder(id);
foreach (var i in o.Items) {
</code>```

...or we could do:

```<code>class Order
{
    int id;
}
</code>```

And use it this way: (2)

```<code>var odr = LoadOrder(id);
var itms = LoadItemsOfOrder(odr);
foreach (var i in itms) {
    .....
</code>```

The first way is more compact and more "OOP-ish", but the second way gives more control on how and when items are requested, e.g. what if now I need to request only the items that have quantity > 3 ? And what if I don't use the Items collection at all (e.g. to display only a list of orders) - I will be doing unnecessary queries to the database.

In my older, big projects I've gone with a hybrid approach - the domain classes are of the first flavor but there are various "load" methods, like "LoadOrder" and "LoadOrderWithItems" or "FillOrderObject".

Now I am working on a small, toy project, no customers and crazy deadlines and got time to think on these issues.

I tried searching the web but it is very hard to find a POCO answer not related to Entity Framework. (I am not working in .net this time, but would like to apply these concepts.)

Question: is there a method which is clearly better than the other, or both are valid and "it depends" on my project, if I am aiming for performance or for code clarity and maintainability?.

Body:
It's never okay to satisfy hypothetical performance goblins at the expense of fewer lines of code or an API that more clearly expresses the relationship between entities.

So, the first example is preferred. Any decent ORM should be able to lazy-load the collection, and some of the more advanced ones will even let define a property on an entity with a custom loading function, also lazy-loaded. That takes care of both of your use cases without breaking encapsulation of the Order class and exposing its inner data structure.


问:
Using mocks to set up object even if you will not be mocking any behavior or verifying any interaction with it?
When building a unit test, is it appropriate to use a mocking tool to assist you in setting up an object even if you will not be mocking any behavior or verifying any interaction with that object?

Here is a simple example in pseudo-code:

```<code>//an object we actually want to mock
Object someMockedObject = new Mock(Object.class);
EqualityChecker checker = new EqualityChecker(someMockedObject);

//an object we are stubbing/mocking only to avoid figuring out how to instantiate or
//tying ourselves to some constructor that may be removed in the future
ComplicatedObject someObjectThatIsHardToInstantiate = new Mock(ComplicatedObject.class);

//set the expectation on the mock
When(someMockedObject).equals(someObjectThatIsHardToInstantiate).return(false);
Assert(equalityChecker.check(someObjectThatIsHardToInstantiate)).isFalse();

//verify that the mock was interacted with properly
Verify(someMockedObject).equals(someObjectThatIsHardToInstantiate).oneTime();
</code>```

Is it appropriate to mock ComplicatedObject in this scenario?

答:
If "you will not be mocking any behavior or verifying any interaction with that object", it sounds like you will not be using that object at all in the unit under test, for that test. Can you just set the reference to null for that test? This makes it very clear that this dependency is irrelevant in this test.

If that is not possible, and you require it to be non-null, it means in fact you are expecting some interaction with it. If your use case really shouldnt be interacting with it at all, it kind of seems like the code under test has a design issue.


问:
Why are more programmers not freelance these days?
Leaving the whole pie to only a few of them, amplifying the huge differences between the two status. Pay is a (huge) one, not having to do overtime is another.

I leave the question open to hopefully get many great answers on all the different subjects that affects that feeling and decision not to go.

While this question is really global, I'll be interested in any studies, facts, articles, opinions regarding local markets such as US, India and even Australia in which I'm in love with.

答:
I'm a contractor in the UK

This is different to freelancing in that the term of the engagement with the client tends to be much longer (6 months and more), but I feel that it's worth mentioning this type of working in the context of the question since it is closely related.

I've been contracting for many years and have been fortunate to avoid any significant break in my work. Almost without exception I have worked through an agency (normally a different one for every fresh contract, but I have been able to get further business through some agencies) and I find that arrangement works well for me and them.

Minimal marketing

I don't have to market myself, other than by keeping my CV up to date and participating in various online communities (mainly Stack Exchange and LinkedIn) which I would do anyway.

Keeping current

I do have to keep myself abreast of the latest developments in my field (I specialise in Java web applications based on open source software) but, again, I'd do that anyway. Typically, I work 9am to 5:30pm Monday to Friday and that is almost continuously spent coding.

Getting paid

I don't have to worry about chasing invoices. I have been fortunate that all the agencies I have dealt with have been reputable and prompt in their payments. They in turn rely on the prompt payment from the clients who tend to be medium to large enterprises (>100 employees).

The downsides

I don't want this to turn into an advert so I'll point out some of the downsides to contracting in the UK:

Taxes are higher than they first appear (but less than equivalent permanent employment)

You have to use an accountant to ensure you're operating your business correctly

You must be prepared to travel if you live outside of a big city (travel and hotel costs eat into your daily rate big time)

You are entirely responsible for arranging your retirement (pension, lottery winnings, iPhone app etc)

No holiday/sick pay (you don't turn up for any reason you don't get paid)

Why aren't there more contractors?

Talking to my fellow contractors and various permanent employees the main reasons for not jumping into contracting seem to be (in order of prevalence):

The constant changing of working environment (travel, colleagues, codebase)

The hassle of running a business

Fear of the unknown and the perceived high risk nature of it

Recent research regarding freelancers

In accordance with the edited question, here are some recent studies that examine the question of freelancers in terms of their presence in the labour market.

Professional Contractors Guild (UK)

Do you think the number of freelancers will rise of the next 10 years? (Poll)

...Dr Bellini’s lecture touched on a
  number of themes, attempting to map
  out the freelance landscape over the
  coming years. He predicts that there
  will be a fundamental shift in working
  patterns, marking the death of the 9-5
  and rise of the freelancer. Dr Bellini
  believes the size of the freelance
  marketplace will double over the next
  10 years.

Prime Minister praises UK freelancers (includes cited figures)

He went on to state: “The 1.4 million
  freelancers in our country make a
  massive contribution to our economy.
  More and more people are choosing
  freelancing, recognising that it
  strikes the right balance between work
  and life in the 21st century, and as
  we go for economic growth this
  Government is getting right behind
  them.”

Analytica (Peer reviewed journal on division of labour)

Getting the message: Communications workers and global value chains (PDF) by Catherine McKercher and Vincent Mosco

They are part of the growing ranks of
  freelance computer  programmers and
  other high-tech workers, who move from
  contract to contract and  from
  employer to employer. Caraway notes
  that, in the current economic
  downturn,  ‘flexibility, or the
  ability of capitalists to mobilise and
  demobilise labour on demand,  has
  taken on a new significance – and a
  new air of inevitability’

These articles all point to a general trend of increasing numbers of freelance workers who wish, or are being forced, to change their working patterns.


问:
Does implementing algorithms improve your programming skills?
I have been self studying algorithms and data structures for some time now and currently enjoying it. Whenever I understand an algorithm, I usually try to code them from scratch for fun and I always will discover some logic I've never thought of before. I'm not so sure, but I always think that when I code algorithms, I am maybe practicing my skills in programming. Is this true? I know they are important, but will my programming skills really improve by coding them?</p>

答:
In theory and academics, it is often most wise to truly understand the details. This is why in university studying computer science, you can get by without having to write much language-specific code. You learn the fundamentals, not, say syntax of C#. With that fundamental information, it should be easy to learn a specific programming language or other tool for that matter.

Understanding the details of different algorithms and data structures is good because they all exist to solve different problems--they don't all exist just because people like inventing them for fun. With this knowledge, as well as practice and experimenting with them, you become more effective in designing solutions in code.

It is rarely necessary or even a good idea to re-implement some standard algorithm or data structure if one already exists. Well designed software is all about reuse. If you are working for a company, they often don't care about your academic or personal benefit, they care about being cost-effective, reusing solutions, etc.

In some cases it may be appropriate to re-implement these things, depending on performance, security, stability requirements and constraints of the system. For example real-time operating systems, hardware drivers, health care, military, traffic hardware or software.


问:
MVC: Controller often simply delegates to Model when notified by View of GUI events. Is this reasonable?
Since I learnt about MVC, I used it for every app I made (which is arguably not the best idea, but that's not the topic of this question). All of them small, 1000 LoC apps. I am using Java and Swing for the GUI.

What usually happens is this:

The view (the GUI class) reports to the controller about any GUI event (most commonly a button click) made. For example when a button is pressed, the view simply calls controller.someButtonPressed() or controller.someOtherButtonPressed(). It's only reaction to user input is reporting to the controller, nothing else.

This, I think, is fine and is proper MVC View implementation. The part I'm having doubts about is the following:

In the controller's someButtonPressed() methods, it very often simply delegates to the model.

For example:

```<code>public void someButtonPressed(){
    model.doTheAppropriateThing();
}
</code>```

Nothing more. No 'decision making' or actual 'interpretation' of what the view reported. Very often, only simple delegation to the model.

Is it considered reasonable when implementing MVC structures and specifically controllers, to have the controller often simply delegate directly to the model in reaction to GUI events? Or does this signal that maybe I'm doing something wrong?

答:
In an ideal world, your model code would be in a separate DLL / Shared Library / Jar file / re-usable module,  and could be included in a system that handles API requests from any client, whether that be an Android App speaking a socket-level protocol or a web page speaking HTTP or some freaky combination of something else.

In those cases, IMHO, the Controller is responsible for making the data that belongs in the View (the app, the web page) appropriately transformed for the view, but also takes care of error handling (HTTP status codes perhaps in one case, and some custom format in another case).

Essentially controllers mediate between models and views,  which means they might need logic that deals with that mediation (data transformation, creating DTOs, returned error information in the appropriate way).  But the logic of what it means in the system when a user takes some action, is the responsibility of the model. The model is the view-and-controller-agnostic representation of the domain. The controller mediates between.


问:
Guidelines for returning collections from public functions

The Problem

Imagine you have a function in a public API that needs to return some kind of collection. Its type is something like

```<code>foo :: a -> b
</code>```

where b is some kind of collection.

As far as I can see, there a three major kinds of collections -- at least those are the ones used most often:

Sequences (order matters, there might be duplicates)

Sets (order doesn't matter, no duplicates)

Maps (elements are key-value pairs, order doesn't matter, no duplicate keys)

What should you use for b in these three cases?. I have considered three alternatives, but there might be more.

A. Just return a list

In this alternative, you just return lists for everything:

foo :: a -> [c]

foo :: a -> [c] (and document that there are no duplicates)

foo :: a -> [(k, c)] (and document that there are no duplicate keys)

The advantage of this is that the client can construct any collection they want from the returned list.

The disadvantage for 2 and 3 is that

the type does not have the "no duplicates" guarantee and that the client has to do more work to get a set/map out of it

construction of the list in 2 and 3 might be less efficient, because something like a union for sets is obviously faster than for lists

you might construct an intermediate list (depends on the problem at hand).

B. Return a concrete type matching the guarantees

In this alternative, you return a type that precisely matches the guarantees you are giving:

foo :: a -> [c] (or maybe foo :: a -> Data.Sequence.Seq c)

foo :: a -> Data.Set.Set c (lazy or strict?)

foo :: a -> Data.Map.Map k c (lazy or strict?)

The advantage is that the type accurately describes the guarantees you want to express and that the client doesn't have to do any extra work.

The disadvantage is that you're locked into a particular implementation. If you just want to switch to a different set implementation, you break the public API. That might be a good thing in case of a switch between lazy and strict, because those can matter for correctness of the calling code. But in general you want to be able to swap implementation without your clients noticing.

C. Let the client decide

In this alternative, you just constrain the return type with a type class and let the client decide on the concrete type:

```<code>1. `foo :: Sequence b c => a -> b`
2. `foo :: Set b c => a -> b`
3. `foo :: Map b c k => a -> b`
</code>```

(The names I used are from collections-api, but it doesn't really matter.)

The advantage of this is that the client can choose which collection type to use.

The disadvantage is that you have no control over the collection you construct anymore. This means, e.g., that you cannot assume laziness or complexity of inserts.
Another problem is that the client can get ambiguous types, e.g., when they immediately fold the returned collection:

```<code>Data.Foldable.fold (foo whatever)
</code>```

Now b is ambiguous.

Are there any other alternatives? What would you recommend?

I don't want foo to be able to return a different kind of collection on every call.
The three cases considered are completely separate.

In each case the question is "if I have a function that needs to return an X, what type should it have?" where X can be a sequence, set, or map (or any other kind of collection you can think of).

答: Why not just have three (or N) separate functions, one for each of the three (or N) separate types of collections?</p>


答:
My suggestion would be to declare an opaque newtype that hides the actual implementation and implement type classes that could be useful to your clients and that you can guarantee to be stable in the future. And you can also export functions that allow conversion of your data type to some standard ones.

This forces clients to use only functions or instances you provide and document, and also allows clients to use standard API such as Foldable:

```<code>module MyMod
    ( MyResult()
    , resultToSet   -- by hiding the internals and exporting the accessor
                    -- explicitly, you can always change the internal
                    -- representation and replace the accessor a function
                    -- with the same signature
    ) where

import Data.Monoid
import qualified Data.Foldable as F
import qualified Data.Set as S

newtype MyResult a = MyResult { resultToSet :: S.Set a }

-- For example, your clients could use `Foldable` and `Monoid` instances:

instance F.Foldable MyResult where
    foldMap f = F.foldMap f . resultToSet

instance (Ord a) => Monoid (MyResult a) where
    mempty = MyResult mempty
    mappend (MyResult x) (MyResult y) = MyResult (x `mappend` y)
</code>```

Update: If you later decide to change the internal representation to HashSet, the module would look like this:

```<code>module MyMod
    ( MyResult()
    , resultToSet   -- by hiding the internals and exporting the accessor
                    -- explicitly, you can always change the internal
                    -- representation and replace the accessor a function
                    -- with the same signature
    ) where

import Data.Monoid
import qualified Data.Foldable as F
import Data.Hashable
import qualified Data.HashSet as HS
import qualified Data.Set as S

newtype MyResult a = MyResult { resultToHashSet :: HS.HashSet a }

-- For example, your clients could use `Foldable` and `Monoid` instances:

instance F.Foldable MyResult where
    foldMap f = F.foldMap f . resultToHashSet

instance (Eq a, Hashable a) => Monoid (MyResult a) where
    mempty = MyResult mempty
    mappend (MyResult x) (MyResult y) = MyResult (x `mappend` y)

-- Reimplementation of functions from the previous version

resultToSet :: (Ord a) => MyResult a -> S.Set a
resultToSet = S.fromList . HS.toList . resultToHashSet
</code>```

The external interface is almost the same (the only change is that the Monoid instance now has slightly different constraints).

Another way that would give clients much flexibility is to let the collection be fully abstract. This can be nicely expressed using monoids. The output of your function will be a polymorphic monoid, we just need a way how to create singletons. For example, if we want to generalize enumFromTo, we could write

```<code>enumCol :: (Enum a, Monoid c) => a -> a -> ((a -> c) -> c)
enumCol f t singleton = mconcat . map singleton $ enumFromTo f t
</code>```

It's then the client responsibility to use a monoid with effective mappend operation.

With RankNTypes the return type could be also encapsulated using type as

```<code>type OutCol e c = (Monoid c) => (e -> c) -> c
</code>```

The additional benefit is that in some cases this can be very effective thanks to laziness. For example, the following returns immediately:

```<code>enumCol 0 (10^20) (First . Just)
</code>```

Title: Guidelines for returning collections from public functions

Body:
The Problem

Imagine you have a function in a public API that needs to return some kind of collection. Its type is something like

```<code>foo :: a -> b
</code>```

where b is some kind of collection.

As far as I can see, there a three major kinds of collections -- at least those are the ones used most often:

Sequences (order matters, there might be duplicates)

Sets (order doesn't matter, no duplicates)

Maps (elements are key-value pairs, order doesn't matter, no duplicate keys)

What should you use for b in these three cases?. I have considered three alternatives, but there might be more.

A. Just return a list

In this alternative, you just return lists for everything:

foo :: a -> [c]

foo :: a -> [c] (and document that there are no duplicates)

foo :: a -> [(k, c)] (and document that there are no duplicate keys)

The advantage of this is that the client can construct any collection they want from the returned list.

The disadvantage for 2 and 3 is that

the type does not have the "no duplicates" guarantee and that the client has to do more work to get a set/map out of it

construction of the list in 2 and 3 might be less efficient, because something like a union for sets is obviously faster than for lists

you might construct an intermediate list (depends on the problem at hand).

B. Return a concrete type matching the guarantees

In this alternative, you return a type that precisely matches the guarantees you are giving:

foo :: a -> [c] (or maybe foo :: a -> Data.Sequence.Seq c)

foo :: a -> Data.Set.Set c (lazy or strict?)

foo :: a -> Data.Map.Map k c (lazy or strict?)

The advantage is that the type accurately describes the guarantees you want to express and that the client doesn't have to do any extra work.

The disadvantage is that you're locked into a particular implementation. If you just want to switch to a different set implementation, you break the public API. That might be a good thing in case of a switch between lazy and strict, because those can matter for correctness of the calling code. But in general you want to be able to swap implementation without your clients noticing.

C. Let the client decide

In this alternative, you just constrain the return type with a type class and let the client decide on the concrete type:

```<code>1. `foo :: Sequence b c => a -> b`
2. `foo :: Set b c => a -> b`
3. `foo :: Map b c k => a -> b`
</code>```

(The names I used are from collections-api, but it doesn't really matter.)

The advantage of this is that the client can choose which collection type to use.

The disadvantage is that you have no control over the collection you construct anymore. This means, e.g., that you cannot assume laziness or complexity of inserts.
Another problem is that the client can get ambiguous types, e.g., when they immediately fold the returned collection:

```<code>Data.Foldable.fold (foo whatever)
</code>```

Now b is ambiguous.

Are there any other alternatives? What would you recommend?

I don't want foo to be able to return a different kind of collection on every call.
The three cases considered are completely separate.

In each case the question is "if I have a function that needs to return an X, what type should it have?" where X can be a sequence, set, or map (or any other kind of collection you can think of).

Body:
My suggestion would be to declare an opaque newtype that hides the actual implementation and implement type classes that could be useful to your clients and that you can guarantee to be stable in the future. And you can also export functions that allow conversion of your data type to some standard ones.

This forces clients to use only functions or instances you provide and document, and also allows clients to use standard API such as Foldable:

module MyMod
    ( MyResult()
    , resultToSet   -- by hiding the internals and exporting the accessor
                    -- explicitly, you can always change the internal
                    -- representation and replace the accessor a function
                    -- with the same signature
    ) where

import Data.Monoid
import qualified Data.Foldable as F
import qualified Data.Set as S

newtype MyResult a = MyResult { resultToSet :: S.Set a }

-- For example, your clients could use `Foldable` and `Monoid` instances:

instance F.Foldable MyResult where
    foldMap f = F.foldMap f . resultToSet

instance (Ord a) => Monoid (MyResult a) where
    mempty = MyResult mempty
    mappend (MyResult x) (MyResult y) = MyResult (x `mappend` y)

Update: If you later decide to change the internal representation to HashSet, the module would look like this:

module MyMod
    ( MyResult()
    , resultToSet   -- by hiding the internals and exporting the accessor
                    -- explicitly, you can always change the internal
                    -- representation and replace the accessor a function
                    -- with the same signature
    ) where

import Data.Monoid
import qualified Data.Foldable as F
import Data.Hashable
import qualified Data.HashSet as HS
import qualified Data.Set as S

newtype MyResult a = MyResult { resultToHashSet :: HS.HashSet a }

-- For example, your clients could use `Foldable` and `Monoid` instances:

instance F.Foldable MyResult where
    foldMap f = F.foldMap f . resultToHashSet

instance (Eq a, Hashable a) => Monoid (MyResult a) where
    mempty = MyResult mempty
    mappend (MyResult x) (MyResult y) = MyResult (x `mappend` y)

-- Reimplementation of functions from the previous version

resultToSet :: (Ord a) => MyResult a -> S.Set a
resultToSet = S.fromList . HS.toList . resultToHashSet

The external interface is almost the same (the only change is that the Monoid instance now has slightly different constraints).

Another way that would give clients much flexibility is to let the collection be fully abstract. This can be nicely expressed using monoids. The output of your function will be a polymorphic monoid, we just need a way how to create singletons. For example, if we want to generalize enumFromTo, we could write

enumCol :: (Enum a, Monoid c) => a -> a -> ((a -> c) -> c)
enumCol f t singleton = mconcat . map singleton $ enumFromTo f t

It's then the client responsibility to use a monoid with effective mappend operation.

With RankNTypes the return type could be also encapsulated using type as

type OutCol e c = (Monoid c) => (e -> c) -> c

The additional benefit is that in some cases this can be very effective thanks to laziness. For example, the following returns immediately:

enumCol 0 (10^20) (First . Just)


答:
I think it's fine if you have methods like the someButtonPressed() in your example. It is important though, that you only have to change the controler but not the model if the logics when pressing someButton changes somewhen in the future. Also the other way around: if the models doTheAppropriateThing() method changes then you don't have to care for the view.

The result is that your view and model are decoupled and when the controller is only "passing" the method calls that's fine.

Title: MVC: Controller often simply delegates to Model when notified by View of GUI events. Is this reasonable?

Body:
Since I learnt about MVC, I used it for every app I made (which is arguably not the best idea, but that's not the topic of this question). All of them small, 1000 LoC apps. I am using Java and Swing for the GUI.

What usually happens is this:

The view (the GUI class) reports to the controller about any GUI event (most commonly a button click) made. For example when a button is pressed, the view simply calls controller.someButtonPressed() or controller.someOtherButtonPressed(). It's only reaction to user input is reporting to the controller, nothing else.

This, I think, is fine and is proper MVC View implementation. The part I'm having doubts about is the following:

In the controller's someButtonPressed() methods, it very often simply delegates to the model.

For example:

```<code>public void someButtonPressed(){
    model.doTheAppropriateThing();
}
</code>```

Nothing more. No 'decision making' or actual 'interpretation' of what the view reported. Very often, only simple delegation to the model.

Is it considered reasonable when implementing MVC structures and specifically controllers, to have the controller often simply delegate directly to the model in reaction to GUI events? Or does this signal that maybe I'm doing something wrong?


问:
A RESTful way to verify server state
I'm interested in building verifications into a REST service to help with service monitoring.

For example, one could run assertions like http://example.com/posts/verify?min-posts=5&since=1-hour-ago which would respond with an error unless 5 new posts had been created in the past hour.

Are there any existing services like this, or best practices? I'm particularly interested in a recommended error code for failed verifications, as I can't really see anything appropriate in the 4xx series. Errors like "Precondition Required" and "Internal Server Error" are more about the actual request or processing of it, than the meaning of it.

答:
Supposing you were to ask for the same verification twice in a row. Would you get the same answer? Would it significantly affect the state of the resources? If you are logically going to get the same answer (which doesn't need to be byte-identical, but rather just “the same” in some higher-level sense) and won't be affecting the state of the resources in any meaningful way then a GET makes a huge amount of sense. That in turn means that any parameters you pass will either be encoded in the path or as query parameters. All of which seems very reasonable to me.

What would the response be? Well, I'd be tempted to say at least consider making it always be 200 and have the response document describe what passed or failed: on one level at least, you're successfully retrieving a document that describes what happened, even if that is a description of a failure.

You could also model a failure as one of the 500-series errors (save the 400-series for “you gave a bad request” problems, such as passing nonsense query parameters) as the problem would be with the state of the service, not the client. But frankly I wouldn't really recommend it; a failure to validate isn't the service's fault as such, but rather just some unfortunate data that the service has been entrusted to look after. (On an operational level, the validation routine itself succeeded, but the data was invalid. It's like a the famous surgeon's dictum: the operation was a success, but the patient died.)

Under no circumstance would I return a 204 No Content from a validation. It's always better to send a message back saying at least a summary of what was checked; the client can throw it away if it wants, but in principle it should be able to show the information to the user.

When working out what response to use, remember that any RESTful web service should be usable by an ordinary web browser with Javascript disabled (though with capabilities that most real browsers don't normally enable, to be fair) at least in principle. Any error responses should therefore be ones that are used for that sort of purpose in a normal web interaction, and this greatly restricts what you can do with the 400-series errors, as most have very stylised client recovery actions.

Title: A RESTful way to verify server state


问:
Can I scrape a website for font stylings?
I am trying to scrape websites for valuable text for example the title of an article, the author's name, and other distinguished text. I cannot always guarantee that this sort of text will have informative tags, and but this needs to be done as quickly as possible. As a possible short cut I think that I could just try to pull the text with unique styling. The title is normally bigger than the body text, and the by-line is normally smaller. Is there a way to quickly pull all of the font stylings of a page and then rank them by size and how often it is used?</p>

答:
That seems like a terribly difficult way of doing things due to the need to completely comprehend all the tricks that you can do in CSS. Detecting headings (
,
, etc.) would be much easier, and if the target website isn't using them, their site will probably not be being very nicely scraped by search engines either. After all, much of the web is actually about encouraging people to put at least some semantic tags on their pages, and headings are some of the most basic semantic tags (“(this part of) this page is about this topic…”). They might not always use the right headings, but if they never use them at all then it is arguably the case that their page is not about anything much at all.

If you're going to do it otherwise, and you've got a library to do all the CSS parsing for you (don't write your own!) then you'll be best off looking at the font-size property of text. Bear in mind that some people like styles that distinguish by colour instead, and others change font size all over the place just because they can, but they really are the exception and not the rule: the rule is that people really do use headings, and usually they use them right.

Body:
That seems like a terribly difficult way of doing things due to the need to completely comprehend all the tricks that you can do in CSS. Detecting headings (<h1>, <h2>, etc.) would be much easier, and if the target website isn't using them, their site will probably not be being very nicely scraped by search engines either. After all, much of the web is actually about encouraging people to put at least some semantic tags on their pages, and headings are some of the most basic semantic tags (“(this part of) this page is about this topic…”). They might not always use the right headings, but if they never use them at all then it is arguably the case that their page is not about anything much at all.

If you're going to do it otherwise, and you've got a library to do all the CSS parsing for you (don't write your own!) then you'll be best off looking at the font-size property of text. Bear in mind that some people like styles that distinguish by colour instead, and others change font size all over the place just because they can, but they really are the exception and not the rule: the rule is that people really do use headings, and usually they use them right.


问:
Languages on a resume: Is it better to put "C/C++" or "C, C++"?
I'm graduating in a couple of weeks, and my resume (as expected) lists the languages that I've had experience with. Previously I've put "C/C++", however back then I didn't have that much experience with these two languages as I do now.

Now that I've formally learned these two languages, it has become evident to me (and anyone who really knows these languages) that they are similar, and completely disimilar at the same time. Sure, most C code is compilable C++ code, but syntax and incorporation of library functions is pretty much where these similarities end. In most non-trivial problems, chances are that the desirable C++ solution will be different from the desirable C solution.

My question:

Will recruiters take note or care about whether you put "C/C++" as opposed to "C, C++"? Will they assume a lack of knowledge of the workings of either because of the inclusion of the first form, or perhaps see the inclusion of the second form as a potential "resume beefer" (listing them as 2 languages, instead of "one")?

Furthermore, for jobs that you've applied to that were particularly interested in these two langauges, did the interview process include questions about the differences between C programming and C++ programming (so, about actual programming techniques, not only the extra paradigms in the latter)?

答:
If you want to remove any ambiguity simply bullet point them:

C

C++

This will cover, all angles including any parsing too.


问:
Should failing unit tests that we're not going to fix be removed?
My coworker likes to see all of our unit tests pass (as would anyone) and he argues that some of the failing tests of a system he wrote are unnecessary "noise" since they all involve the validity of the data and a separate system in our stack is supposed to be responsible for validation.

Personally, I think keeping the tests allows you to at least understand/acknowledge some of the failing points even if you consciously choose not to fix them.

Is he right in wanting them removed since they are "noise" compared to the other tested functionality and will probably never be fixed?

Just for context. Here are some concrete examples. They all involve code paths that are used, but passing non-validated data into the routines causes unexpected behaviors.:

passing in NaN results in a false positive.

passing in a value that overflows a double's significant figures results in false when true should have been returned. Rounding should not occur.

"139.9999999999999" -> Double.TryParse() -> 139.9999999999999

"139.99999999999999" -> Double.TryParse() -> 140

答:
In general you should avoid dead code of all kinds. Regardless if its production or test code. Even if you find convincing arguments for keeping a particular code around, the main thing other developers see is that dead code is acceptable and they will do it as well. And because they might not be aware of your justifications they will do it for much less profound reasons. And it's true that will add to the overall noise. See broken window theory.

If you want to keep this dead test code around, just to be reminded about the assumptions your tested methods make about the input parameters, then go ahead document these assumptions for the method itself! Or to make it more explicit you can write explicit assertions in your method, which can serve as a documentation as well as a debug tool when enabled during debugging. There are even precondition frameworks available if you want to go that route, but that is not really necessary.

Oftentimes dead code can be removed without replacement. At other times it still can be deleted but should be replaced with some documentation or some real code (like assertions). If you have to keep dead code around make sure you document the reasons in doing so right above the offending code block.


问:
How do languages with Maybe types instead of nulls handle edge conditions?
Eric Lippert made a very interesting point in his discussion of why C# uses a null rather than a Maybe<T> type:

Consistency of the type system is important; can we always know that a non-nullable reference is never under any circumstances observed to be invalid? What about in the constructor of an object with a non-nullable field of reference type? What about in the finalizer of such an object, where the object is finalized because the code that was supposed to fill in the reference threw an exception? A type system that lies to you about its guarantees is dangerous.

That was a bit of an eye-opener.  The concepts involved interest me, and I've done some playing around with compilers and type systems, but I never thought about that scenario.  How do languages that have a Maybe type instead of a null handle edge cases such as initialization and error recovery, in which a supposedly guaranteed non-null reference is not, in fact, in a valid state?

答:
C++ does it by having access to the initializer that occurs before the constructor body.  C# runs the default initializer before the constructor body, it roughly assigns 0 to everything, floats become 0.0, bools become false, references become null, etc.  In C++ you can make it run a different initializer to ensure a non-null reference type is never null.

```<code>class Foo { Foo(int i) { throw new Exception("Never finishes"); }
class Bar { Bar(string s) { } }

class Broken
{
    val foo: Foo  // where Foo and Bar are non-nullable reference types
    val bar: Bar

    Broken() :
        foo = new Foo(123),// roughly causes a "goto destroy_foo;"
        bar = new Bar("never executes") { }

    // This destructory-function never runs because the constructor never completed
    ~Broken()
    // This is made-up syntax:
    // :
    // destroy_bar:
    // bar.~Bar();
    // destroy_foo:
    // foo.~Foo();
    {
    }
}
</code>```

Body:
C++ does it by having access to the initializer that occurs before the constructor body.  C# runs the default initializer before the constructor body, it roughly assigns 0 to everything, floats become 0.0, bools become false, references become null, etc.  In C++ you can make it run a different initializer to ensure a non-null reference type is never null.

class Foo { Foo(int i) { throw new Exception("Never finishes"); }
class Bar { Bar(string s) { } }

class Broken
{
    val foo: Foo  // where Foo and Bar are non-nullable reference types
    val bar: Bar

    Broken() :
        foo = new Foo(123),// roughly causes a "goto destroy_foo;"
        bar = new Bar("never executes") { }

    // This destructory-function never runs because the constructor never completed
    ~Broken()
    // This is made-up syntax:
    // :
    // destroy_bar:
    // bar.~Bar();
    // destroy_foo:
    // foo.~Foo();
    {
    }
}


问:
Do modular PHP frameworks really improve applications?
One of the goals of modular frameworks like Kohana or Alloy is to make it easy to add and remove components (i.e. "plugins" or "modules").

However, in all the larger projects I have ever worked - the system often becomes dependent on the modules it is built on. After all, that is why they are there - to build with them.

So, I'm wondering if the concept of building distinct separate sections of a web application as independent modules is even a good idea to begin with? For example, we may build a general user, forum, and blog module - but each project is different and usually involves building many layers of abstractions to add new features - or editing the files directly to customize them. I can't re-use the same module on multiple projects.

In other words, they are no longer just a plug-in-play add-on to the site.

Now I'm not confusing this with proper class design to ensure un-coupled MVC and library logic. But I'm wondering if "MMVC" was a superfluous effort to apply proper class design concepts to application design as well. After all, many migration systems or database libraries like Doctrine require all the relations spelled out in the models from day one, thereby linking the entities.

Is it one of those things that sounds like a good idea when the project starts, but eventually is shown to be a useless feature? Do modules have their place in systems like wordpress - but not in frameworks where you are obviously building something custom?

答:
The ubiquitous MVC pattern of today's frameworks is a form of forced modularity...but it's not the kind of feature-based modularity that most people think of when they think of the word.  Old-school applications were traditionally a lot more feature-modular, which made them more transparent and better reflections of the user experience.

Feature-based modularity defines groups of source files and/or code structures based on application features, for example:

a login process

a new account registration process

a discussion board

a searchable product catalog

a new order entry process

etc.

So for a login process, you might have:

source files named things like "login.php" and/or "class.login.php" and/or "login_view.php", etc.

code functions named things like "RenderLoginForm()" and/or "ProcessLoginForm()", etc.

code classes named things like "LoginProcess", etc.

To be truly modular, each module needs to interoperate with central application controllers, automated test scripts, etc.  To do this, you might have:

The entire module wrapped in a class/function that can be created/called by a central routing-type program

The entire module contained in a source file that can be called or included by a central routing-type program

Input and output parameters that can be passed and returned by the functions to indicate which records are affected, what the module does, what happens before and after, etc.

MVC modularity neatly separates languages: SQL (in the model), HTML/CSS/JS (in the view), and PHP/Python/Ruby (in the controller).  But MVC knows nothing about the features.  A truly feature-modular application will have a unique architecture that can only be designed by someone who understands the user experience and business needs.  MVC, like object-oriented programming, is merely a design pattern.  It's a poor substitute for a true, unique, relevant, modular application architecture.

MVC rules the landscape today and, at times, it is a wonderful pattern.  But someday people will wake up and throw off its overused, arbitrary, clumsy shackles and rediscover unique, custom application architectures.


问:
MVC: Does the Controller break the Single Responsibility Principle?
The Single Responsibility Principle states that "a class should have one reason the change".

In the MVC pattern, the Controller's job is to mediate between the View and the Model. It offers an interface for the View to report actions made by the user on the GUI (e.g. allowing the View to call controller.specificButtonPressed()), and is able to call the appropriate methods on the Model in order to manipulate it's data or invoke it's operations (e.g. model.doSomething()).

This means that:

The Controller needs to know about the GUI, in order to offer the View a suitable interface to report user actions.

It also needs to know about the logic in the Model, in order to be able to invoke the appropriate methods on the Model.

That means that is has two reasons to change: a change in the GUI, and a change in the buisness logic.

If the GUI changes, e.g. a new button is added, the Controller might need to add a new method to allow the View to report a user press on this button.

And if the business logic in the Model changes, the Controller might have to change in order to invoke the correct methods on the Model.

Therefore, the Controller has two possible reasons to change. Does it break SRP?

答:
If a class has "two possible reasons to change", then yes, it violates SRP.

A controller should usually be lightweight and have the single responsibility of manipulating the domain/model in response to some GUI-driven event. We can consider each of these manipulations to basically be use cases or features.

If a new button is added on the GUI, the controller should only have to change if that new button represents some new feature (i.e. opposed to just the same button that existed on screen 1 but didnt exist yet on screen 2, and it is then added to screen 2). There would need to be a corresponding new change in the model also, to support this new functionality/feature.  The controller still just has the responsibility of manipulating the domain/model in response to some GUI-driven event.

If the business logic in the model changes due to a bug being fixed, and it requires the controller to change, then this is a special case (or perhaps the model is violating open-closed principal).  If the business logic in the model changes to support some new functionality/feature, then that doesnt necessarily impact the controller--only if the controller needs to expose that feature (which would almost always be the case, otherwise why would it be added to the domain model if it wont be used).  So in this case the controller has to be modified also, to support manipulating the domain model in this new way in response to some GUI-driven event.

If the controller has to change because, say, the persistence layer is changed from a flat file to a database, then the controller is certainly violating SRP. If the controller always works at the same layer of abstraction, then that can help in achieving SRP.


答:
If you continue consequently to reason about the SRP you will come to notice that "single responsiblity" is actually a spongy term. Our human brain is somehow able to distinguish between different responsibilities and multiple responsibilities can be abstracted into one "general" responsibility. For example, imagine in a common 4 person family there is one familiy member responsible for making the breakfast. Now, to do this, one has to boil eggs and toast bread and of course set up some healthy cup of green tea (yes, green tea is best). This way you can break "making breakfast" down into smaller pieces which are together abstracted to "making breakfast". Notice that each piece is also a responsibility that could e.g. be delegated to another person.

Back to the MVC: if mediating between model and view ist not one responsibility but two, then what would be the next abstraction layer above, combining those two? If you can't find one you either didn't abstract it correctly or there is none which means you got it all right. And i feel that is the case with a controller, handling a view and a model.

Title: MVC: Does the Controller break the Single Responsibility Principle?

Body:
The Single Responsibility Principle states that "a class should have one reason the change".

In the MVC pattern, the Controller's job is to mediate between the View and the Model. It offers an interface for the View to report actions made by the user on the GUI (e.g. allowing the View to call controller.specificButtonPressed()), and is able to call the appropriate methods on the Model in order to manipulate it's data or invoke it's operations (e.g. model.doSomething()).

This means that:

The Controller needs to know about the GUI, in order to offer the View a suitable interface to report user actions.

It also needs to know about the logic in the Model, in order to be able to invoke the appropriate methods on the Model.

That means that is has two reasons to change: a change in the GUI, and a change in the buisness logic.

If the GUI changes, e.g. a new button is added, the Controller might need to add a new method to allow the View to report a user press on this button.

And if the business logic in the Model changes, the Controller might have to change in order to invoke the correct methods on the Model.

Therefore, the Controller has two possible reasons to change. Does it break SRP?


答:
The controller doesn't violate SRP.  As you state, its responsibility is to mediate between the models and the view.

That being said, the issue with your example is that you are tying controller methods to logic in the view, ie controller.specificButtonPressed. Naming the methods this way ties the controller to your GUI, you have failed to properly abstract things.  The controller should be about performing specific actions, ie controller.saveData or controller.retrieveEntry. Adding a new button in the GUI doesn't necessarily mean adding a new method to the controller.

Pressing a button in the view, means to to do something but whatever that is could easily have been triggered in any number of otherways or even not through the view.

From the Wikipedia article about SRP

Martin defines a responsibility as a reason to change, and concludes
  that a class or module should have one, and only one, reason to
  change. As an example, consider a module that compiles and prints a
  report. Such a module can be changed for two reasons. First, the
  content of the report can change. Second, the format of the report can
  change. These two things change for very different causes; one
  substantive, and one cosmetic. The single responsibility principle
  says that these two aspects of the problem are really two separate
  responsibilities, and should therefore be in separate classes or
  modules. It would be a bad design to couple two things that change for
  different reasons at different times.

The controller isn't concerned with what is in the view only that when one of its methods is called that it provide specified data to the view.  It only needs to know about the model's functionality so far as it knows that it needs to call methods that they will have.  It doesn't know anything more than that.

Knowing that an object has a method available to call is not the same as knowing its functionality.


问:
Can static and dynamically typed languages be seen as different tools for different types of jobs?
Yes, similar questions have been asked but always with the aim of finding out 'which one is better.'

I'm asking because I came up as a dev primarily in JavaScript and don't really have any extensive experience writing in statically typed languages.

In spite of this I definitely see value in learning C for handling demanding operations at lower levels of code (which I assume has a lot to do with static vs dynamic at the compiler level), but what I'm trying to wrap my head around is whether there are specific project contexts (maybe certain types of dynamic data-intensive operations?) involving things other than performance where it makes a lot more sense to go with Java or C# vs. something like Python.

答:
They're different tools, but it's not by performance. It's all about complexity.

Dynamic languages usually aim maximum flexibility, and it brings lack of validation and a sort of guarantee. Then, it's very powerful in small scale programs, but it becomes almost impossible to maintain large scale programs (complexity).

Static languages usually aim maximum validation. Their first goal is usually catching errors (or bugs) as early as possible. Many guarantees are made for the validation. Then it's harder to learn and start, but as programs goes larger, it provides better program validation with far less cost (coding efforts).

As a result, dynamic languages usually fit for small (I mean very small) programs such as dynamic web pages, web browser DSL (not for browser applications!) or shell scripting. Static languages suit better for system programmings or any other stuffs.

Above descriptions are something about very purely dynamic or static languages. Most real-life languages are in between them, and shows various characteristics.

See here for more details:
https://softwareengineering.stackexchange.com/a/105417/17428

OwnerDisplayName: Erik  Reppen


问:
What is better for prototyping: a statically-typed language, or a dynamically-typed one?
When working out the design for a new system, is it better to start with a statically-typed language (like Haskell), or a dynamically-typed language (like Ruby)?

Arguments I can think of:

With a static language, you can quickly create a specification and scope for what the program will do.  With a dynamic language, you can quickly create a working demo to present to the customer for review.

With a dynamic language, you often avoid having to rearrange data structures and refactor code when you change your design.  With a static language, you can define types before implementation, keeping the code to maintain very small.

With a static language, you have to figure out in advance what your program will do.  With a dynamic language, you can start writing code, and let the design grow organically.  As Paul Graham says in Hackers and Painters:

A programming language is for thinking of programs, not for expressing
  programs you've already thought of.

With a static language, the compiler can help identify many types of bugs.  With a dynamic language, you can begin testing and finding bugs sooner.

Static and dynamic typing both have advantages and disadvantages as far as prototyping is concerned.  However, they both seem to me like equally valid approaches.  Based on your experiences, which one is ultimately better?

Notes

Prototyping in natural language

A third type of language to consider: natural language.  Instead of prototyping in code, one can prototype in writing.  The customer can then read your documentation and critique your design early on, but cannot toy around with a working demo.  If well-written, the documentation can make implementation in any language straightforward.  Caveats:

The documentation may be tedious to read through, and difficult to digest without being able to see it.  I speculate that a customer would rather experiment with something that works rather than read a wall of text (and images).

Prototyping an application in English rather than in type definitions is more verbose and less concrete.

Haskell types are descriptive

Note that types are particularly descriptive in Haskell, more so than in many static languages like C++ and Java.  For example, suppose I have a function with this type signature in Haskell:

```<code>foo :: forall a. [a] -> a
</code>```

A function that, for any type a, takes a list of items of type a and returns a value of type a.

Even without knowing the function's name, I know for a fact that:

It does not perform input/output or modify any values (well, unless it uses unsafePerformIO incorrectly), because Haskell is purely functional.

It cannot treat the items as, say, integers, because it has to support any type.

It has to use the input list (that, or throw an exception or go into an infinite loop).  Otherwise, where would it get a value of type a from?

Therefore, the only thing this function could possibly do (other than fail) is extract an item out of the input list and return it.  Although I still do not know which item it will use, [a] -> a tells me just about everything else.

答:
Whatever language which you're most familiar with.

Dynamic vs static really doesn't matter. Functional vs OO really doesn't matter. Best fit, features or whatever they are usually all meaningless.

The only point of prototyping is speed of implementation (code-writing) because you need to change program a lot. And you should be fastest with your best language.

If you have two best languages in both of dynamic and static, I would bet on static one. Because static one usually can handle complexity, while dynamic one fails at some point. And nobody really know how large prototype will grow up.


问:
Should duck typing affect naming conventions?
I'm a C++/C# developer and recently I've started to learn Python. I think I understand the concept of duck typing right now except for one thing.

When I'm coding in C++ or C# I sometimes create completely unrelated classes that have similar methods with similar signatures, for example: Create(), Open(), Close(), ProcessData(), etc. It's not a big deal in C++ or C# (unless you want to mess with C++ templates), but in languages with duck typing like Python this could cause a disaster. Consider the following example:

```<code>class DbTransaction:
    def rollback(self):
        pass

class SourceControlChangeset:
    def rollback(self):
        pass

def rollback_transaction(transaction):
    transaction.rollback()

transaction = DbTransaction()
changeset = SourceControlChangeset()
rollback_transaction(transaction)
rollback_transaction(changeset) # Oops!
</code>```

Maybe be example is a bit artificial, but I think this could happen pretty easily in a big project with many classes.

What should I do in this situation? I think that type checking is not "pythonic" so my only idea is to change naming convention for class methods like this:

```<code>class DbTransaction:
    def rollback_transaction(self):
        pass

class SourceControlChangeset:
    def rollback_changeset(self):
        pass
</code>```

Any ideas?

答:
In Clean Code, Robert Martin argues that even with static typing, you should avoid what he calls "punning," meaning giving the same name to two methods that aren't semantically similar.  That means if you consider transaction.rollback and changeset.rollback to be semantically different, you should try to choose another name for one of them, whether you are doing duck typing or not.

In your particular example the name makes the semantics of each case obvious, even though the context is different, so it's okay to leave the name the same.  You're mostly concerned with preventing accidentally passing one kind of object into a context meant for the other.

To be blunt, that's the trade-off you make when choosing duck typing.  You increase the risk of using the wrong type, which requires somewhat more testing, but in exchange you gain increased reusability with less hassle.  If you want the benefits of strong static typing, you should choose your language and architecture accordingly.  You can't have your cake and eat it too.


问:
Is ok to throw exception in normal code path which eliminate a possible programmer error?
I know that exception should be thrown in exceptional case (e.g. out of memory, programmer error). For these cases, I don't need to worry about performance throwing these exception.

But what happen if use exception in normal code path?

In my case, use it to stop user code supplied function.

So for given code, is foo better or foo2 better?

It is very likely that outputFunc will return false / throw exception.

```<code>// library provided function
void foo(std::function<void(std::function<bool(int)>)>);

// how user suppose to use it
foo([](std::function<bool(int)> outputFunc){
    while (/*condition*/)
    {
        // user have to check the return value and stop work when it return false
        if (!outputFunc(/*some value*/)) return;
    }
});

// library provided function
void foo2(std::function<void(std::function<void(int)>)>);

// how user suppose to use it
foo2([](std::function<void(int)> outputFunc){
    while (/*condition*/)
    {
       // this will throw exception and handled internally when it should stop
       // user does not have to check the return value but they need to write exception-safe code
        outputFunc(/*some value*/));
    }
});
</code>```

In my case, the use of exception eliminate a possible programmer error (by not checking return value of outputFunc) and make code easier to write (no need to check return value)

And the exception is throw/catch internally, no user code required to deal with them (except they need to write exception-safe code in the lambda, but we should always write exception-safe code)

答:
If a function cannot do what it is supposed to do and returning a value will be misleading, then throwing an exception seems to be the only other option.

This situation ideally would never happen, and if it does it should represent a problem in the system's environment or bug in the code. Ideally you should try to work around it by doing some prevalidation yourself. For example call some function to check whether the inputs/state is valid for the function you really want to call. That validation function would return a boolean, and depending on that result, you will know whether or not to call the intended function.


问:
Unit Testing: How much more code?
I'm fairly new to unit testing. In school it's always been, "hey it works, onward!" But I've started to write professionally, and even at work that's been basically the mantra. However, I've started to see the validity of unit testing and TDD. I've come to a realization, that when I write maybe a 20 line piece of code, I'll usually write a 100-250 lines of code testing those lines of code. Is this about average? Are there better best practices of unit testing that I'm not aware of? </p>

<p>Any way, I thought it was an interesting observation and was wondering, on average how much more code do you write when you write your unit tests? </p>

答:
In general, I put the line at "unit tests should be about half the size of the code they test". Occasionally it will be more for vital/complex code, but more often than not it just means I'm testing too much. That is, I'm writing a bunch of tests that are unlikely to find or prevent bugs.

I don't do much in python, and I don't know how you're writing tests, so I can't say if you're doing something poorly/inefficiently. It is possible that you're missing a good mocking framework. More likely, you just have hard to test code (perhaps because of what it's doing, perhaps because it's poorly designed) and are testing way too much.

Title: Unit Testing: How much more code?


问:
If null is bad, why do modern languages implement it?
I'm sure designers of languages like Java or C# knew issues related to existence of null references (see Are null references really a bad thing?). Also implementing an option type isn't really much more complex than null references.

Why did they decide to include it anyway? I'm sure lack of null references would encourage (or even force) better quality code (especially better library design) both from language creators and users.

Is it simply because of conservatism - "other languages have it, we have to have it too..."?

答:
Null/nil/none itself is not evil.

If you watch his misleadingly named famous speach "The Billion dollar Mistake", Tony Hoare talks about how allowing any variable to be able to hold null was a huge mistake. The alternative - using Options - does not in fact get rid of null references. Instead it allows you to specify which variables are allowed to hold null, and which aren't.

As a matter of fact, with modern languages that implement proper exception handling, null dereference errors aren't any different than any other exception - you find it, you fix it. Some alternatives to null references (the Null Object pattern for example) hide errors, causing things to silently fail until much later. In my opinion, its much better to fail fast.

So the question is then, why do languages fail to implement Options? As a matter of fact, the arguably most popular language of all time C++ has the ability to define object variables that cannot be assigned NULL. This is a solution to the "null problem" Tony Hoare mentioned in his speech. Why does the next most popular typed language, Java, not have it? One might ask why it has so many flaws in general, especially in its type system. I don't think you can really say that languages systematically make this mistake. Some do, some don't.


答:
For SQL Lite, testing level is high ... and I mean it!

http://www.sqlite.org/testing.html

As of version 3.8.0, the SQLite library consists of approximately 84.3 KSLOC of C code. (KSLOC means thousands of "Source Lines Of Code" or, in other words, lines of code excluding blank lines and comments.) By comparison, the project has 1084 times as much test code and test scripts - 91452.5 KSLOC.

Title: Unit Testing: How much more code?

Body:
I'm fairly new to unit testing. In school it's always been, "hey it works, onward!" But I've started to write professionally, and even at work that's been basically the mantra. However, I've started to see the validity of unit testing and TDD. I've come to a realization, that when I write maybe a 20 line piece of code, I'll usually write a 100-250 lines of code testing those lines of code. Is this about average? Are there better best practices of unit testing that I'm not aware of? </p>

<p>Any way, I thought it was an interesting observation and was wondering, on average how much more code do you write when you write your unit tests? </p>


答:
There is a continuum that situations like this fall into. If you need the functionality the unit tests test, you should obviously keep them. If you will never use it ever, ever, ever again, and you know this and are absolutely, positively, 100% sure of it, you should throw those unit tests out. For any other certainty level, the answer is not so cut-and-dry.

If you are going to use the functionality, but not right now, you may want to keep the unit tests, unless they are interfering with other unit tests or code validation. One testing suite I have been using, BusterJS for Node, has a method to put unit tests "on hold" by putting 2 slashes in front of the name, inside its string. In effect, you are "commenting the test out", though Buster still knows it's there and shows it to you. Your testing suite may have something like this: if it dooes, USE IT!

If there is the tiniest chance that you will ever use the functionality, decide how important it is that it be tested were you to use it, how intrusive the tests are, and how much bloat they cause, then decide from there. Also keep in mind that all this code has a cost in terms of readability and space, though usually there are ways to definitively separate it from the rest of the code and it probably won't take up enough extra space to worry about. Performance usually isn't a problem, as the app is usually smart enough to not run the tests while it's running production code.

Finally, remember that you may be able to have the best of both worlds: the unit tests exist and are kept up-to-date, but are either optional in your test suite or not actually performed. How you do this is up to you, but most programming languages have a concept called "commenting". This is probably how you are writing your documentation, so why not use it for stuff you need or want but aren't using right now? Then, if you ever need to use the test, just make it not a comment anymore. Remember to keep the tests as up-to-date as necessary or desired by periodically testing the tests themselves.

Title: Should failing unit tests that we're not going to fix be removed?

Body:
My coworker likes to see all of our unit tests pass (as would anyone) and he argues that some of the failing tests of a system he wrote are unnecessary "noise" since they all involve the validity of the data and a separate system in our stack is supposed to be responsible for validation.

Personally, I think keeping the tests allows you to at least understand/acknowledge some of the failing points even if you consciously choose not to fix them.

Is he right in wanting them removed since they are "noise" compared to the other tested functionality and will probably never be fixed?

Just for context. Here are some concrete examples. They all involve code paths that are used, but passing non-validated data into the routines causes unexpected behaviors.:

passing in NaN results in a false positive.

passing in a value that overflows a double's significant figures results in false when true should have been returned. Rounding should not occur.

"139.9999999999999" -> Double.TryParse() -> 139.9999999999999

"139.99999999999999" -> Double.TryParse() -> 140


问:
How to make your JavaScript private?
I wanted to know if there is a way to make your JavaScript private from client side?</p>

答: You cannot make client-side javascript private.  You can obscure it by running a program that will shorten all the variable names into meaningless names, but by definition if it can be read and executed by a browser, so can it be read by a person.</p>

Title: How to make your JavaScript private?


答:
The obvious answer is that if the behaviors are not going to be fixed, then in fact their actual behavior is not "unexpected", but rather "expected": it is understood to be in a certain way, and it is understood why it is that way, and it is understood that it will continue that way (won't be "fixed").

Such a behavior should be codified as the expected behavior which the unit test validates.

If passing NaN to a function produces a false positive, then write the regression test so that it validates this. Then one day if passing NaN to that function produces a negative, something changed (possibly in a broken way).


问:
Why are more programmers not freelance these days?
Leaving the whole pie to only a few of them, amplifying the huge differences between the two status. Pay is a (huge) one, not having to do overtime is another.

I leave the question open to hopefully get many great answers on all the different subjects that affects that feeling and decision not to go.

While this question is really global, I'll be interested in any studies, facts, articles, opinions regarding local markets such as US, India and even Australia in which I'm in love with.

答:
Consultants who are making money probably stay with it and those that don't, go get jobs. That will throw off the averages. Why be a consultant if you can make more money on the job?

All things being equal, I'd rather be writing code than continuously trying to explain to people that I can write code/looking for work. If a firm is doing this for you, you're not making that much more than an employee after they take their cut.

Now if you want the flexibility to one day start you own company, I would do contract work.

Edit: I use to be able to get contract work, but I had a contact that did IT consulting. When he had clients that needed custom programming, he'd call me.