问:
Untyped lambda calculus: Why is call-by-value strict?
I'm currently reading Benjamin C. Pierce's “Types and Programming Languages”. Before really getting into type theory it explains lambda calculus and evaluation strategies.

I am a bit confused by the explanation of call by name vs call by value in this context.

The two strategies are explained in the following manner:

call by name

Like normal order in that it chooses the leftmost, outermost redex first, but more restrictive by not allowing reductions inside abstractions. An example:

```<code>  id (id (λz. id z))
→ id (λz. id z)
→ λz. id z
</code>```

call by value

Only the outermost redexes are reduced and a redex is reduced only when its right-hand side has already been reduced to a value—a term that is finished computing and cannot be reduced any further. An example:

```<code>  id (id (λz. id z))
→ id (λz. id z)
→ λz. id z

(identical to the call by name evaluation)
</code>```

Ok, so far so good. But this is followed by the following paragraph:

The call-by-value strategy is strict, in the sense that the arguments to functions are always evaluated, whether or not they are used by the body of the function. In contrast, non-strict (or lazy) strategies such as call-by-name and call-by-need evaluate only the arguments that are actually used.

I know what call-by-value and call-by-name means practically, from having used (among others) C and Haskell, but I cannot see why the evaluation strategy explained above leads to this in the lambda calculus. Is this an additional rule that always accompany call-by-value, or does if follow from the reduction strategy outlined above?

Especially since the reduction steps in the examples are identical, I fail to see the difference between the two strategies and would love if someone could help me gain some intuition.

答:
Yes, the evaluation strategy as described leads to strict semantics, and the examples are spectacularly badly chosen to conceal the difference between the two semantics. I think it goes something like this:

```<code>id (id (λz. id z))  # strict means we evaluate the right hand side
→ id (λz. id z)     # RHS has been reduced (id (λz. id z)) → (λz. id z) by inner id
→ λz. id z          # now we have called the outer id to obtain the final value

id (id (λz. id z))  # normal form means we call the outer id and pass RHS as a closure
→ id (λz. id z)     # outer id just returned its argument unevaluated → id (λz. id z)
→ λz. id z          # now same thing is repeated with inner id
</code>```

So the derivation steps look syntactically the same, but different things are happening. Under the lazy evaluation scheme, id doesn't actually force evaluation of its argument: it simply returns that argument itself. So not only do id x and x yield the same value, but they are actually equivalent: id x really yields x itself, and then x yields its value later when actually needed. So likewise, id (id (λz. id z)) simply yields the unevaluated right hand side (id (λz. id z)).

What's confusing in the example is that it's based on nesting the same function, which is just id, such that two different reductions both yield id (λz. id z). In one this is just a copy of the inner id expression, and in the other, it's the value of the inner expression, being passed an argument to the outer id.

Body:
Yes, the evaluation strategy as described leads to strict semantics, and the examples are spectacularly badly chosen to conceal the difference between the two semantics. I think it goes something like this:

id (id (λz. id z))  # strict means we evaluate the right hand side
→ id (λz. id z)     # RHS has been reduced (id (λz. id z)) → (λz. id z) by inner id
→ λz. id z          # now we have called the outer id to obtain the final value

id (id (λz. id z))  # normal form means we call the outer id and pass RHS as a closure
→ id (λz. id z)     # outer id just returned its argument unevaluated → id (λz. id z)
→ λz. id z          # now same thing is repeated with inner id

So the derivation steps look syntactically the same, but different things are happening. Under the lazy evaluation scheme, id doesn't actually force evaluation of its argument: it simply returns that argument itself. So not only do id x and x yield the same value, but they are actually equivalent: id x really yields x itself, and then x yields its value later when actually needed. So likewise, id (id (λz. id z)) simply yields the unevaluated right hand side (id (λz. id z)).

What's confusing in the example is that it's based on nesting the same function, which is just id, such that two different reductions both yield id (λz. id z). In one this is just a copy of the inner id expression, and in the other, it's the value of the inner expression, being passed an argument to the outer id.


问:
Is Objective C a reasonable way to learn C?
I want to learn C but I tend to learn best when I have a project to work on. I've never done iPhone development, so I'm hoping to kill two birds with one stone. Will learning objective c also teach me to program c reasonably well, or are they too dissimilar?

EDIT: I'm mostly wondering if objective-c/iphone-development would teach me all the little gotcha's that are inherent to c. I come from a .Net background so I haven't done much in terms of memory management or working with pointers.

答:
The best way to learn a language is to use the language you wish to learn, not some other language, regardless of how much the two have in common.

In particular, it you use Objective C, you will learn the Objective C way of doing things, not the C way.

ContentLicense: CC BY-SA 3.0


问:
How long and what type of complexity would have been involved in Chris Sawyer writing most of rollercoaster tycoon in assembler?
From this question, I have another question about...

How long and what type of complexity would have been involved in Chris Sawyer writing most of rollercoaster tycoon in assembler?

In order to specify and break this question down, I am interested in;

Approximately how many man hours (have a guess) do you estimate it would have taken Chris to write the game by himself? Or alternatively give an approximate percentage of the ratio of assembler coding hours to say, writing the whole thing in C/C++.

Do the programmers that know assembler well think of this as an overly complex task for such a low level language abstraction? Apart from performance benefits is this just a freakish natural ability that Chris has, or a skillset worthy of learning to that extent? I'm interested if people think the complexity/performance thing is worth learning assembler that well (in order to write), or is it only "worth it" if you have a lot of naturally developed skills in assembler (presumably from working with hardware/hardware drivers/electronics/etc).

答:
Another person known for writing a lot of Windows programs in assembler is Steve Gibson, author of SpinRite, ShieldsUp! and other utilities.  He discusses his love of assembly language here.

Randy Hyde (whom I used to know way back when we were both writing 6502 assembly code for the Apple II) has a new online book called Windows Programming in Assembly Language.  He is a big proponent of using fancy macros (including looping constructs) to make assembly programming more like using a high-level language.  Sawyer probably used a similar approach to be more productive.

ContentLicense: CC BY-SA 2.5


答:
Based on your edit, I would say that Obj-C is not the best way to go.

Obj-C has a lot of nice things as part of the framework that make it a higher level language, which will mask the very gotchas that you want to experience in C. In particular, memory management in Obj-C is a big topic in its own right, and it is very different from what you would typically be doing in C.

Just because something is a superset, it does not mean that you will be utilizing the whole original set.

I would advise you to figure out what it is exactly that you want to do with C, and tackle it directly.

Title: Is Objective C a reasonable way to learn C?

Body:
I want to learn C but I tend to learn best when I have a project to work on. I've never done iPhone development, so I'm hoping to kill two birds with one stone. Will learning objective c also teach me to program c reasonably well, or are they too dissimilar?

EDIT: I'm mostly wondering if objective-c/iphone-development would teach me all the little gotcha's that are inherent to c. I come from a .Net background so I haven't done much in terms of memory management or working with pointers.


问:
Are there any tools for remote coding interview?
Firstly, I'm not exactly sure if this question is a better fit over here, or on workplace.SE. So forgive me if it is in the wrong place.

We are interviewing some candidates for a development position, and currently they are not in our city.

We would like to give them simple coding tests to see how they will perform on the typical issues that we face in our daily work.

Are there any specific tools geared towards this? Right now we are using Skype and I feel this tends to decrease the performance of a lot of developers since they tend to be shy, and often can't work when someone is directly staring at them.

The problem with sending them the test questions by email are as follows:

It is not possible to know what their thought process is, sine we just see the end result. There is no discussion, or clarification of the question, which is an Important step.

There is no guarantee that the problems were solved by the candidates themselves. They could send it to a smarter friend, and we wouldn't be able to know.

How are these problems usually solved?

答:
ProgBuddy allows you to do remote interview in real-time over the internet. It's a web-based Linux powered collaboration tool which includes complete operating system sandbox without need to give the job candidate access to your company internal infrastructure. You can code and text/audio/video chat with the other party directly in your browser - no need to install any plugins. You and your job candidate both see the same text or graphical desktop where you can do the interview.

Here are some of the key features:

Linux on AMD64 (x86-64) architecture

desktop and console access

instant availability

5GB of non-persistent space

WebDAV access

support for variety of programming languages (C, C++, GCC toolchain, Java, PHP, CakePHP, Python, Django, Ruby, Ruby on Rails and more)

audio and video conferencing directly in your browser

session recording


问:
Should I allow my client to self host?
I'm just starting out as a web designer. I'm trying to build up a portfolio for my own website.

I'm concerned about designing a site and handing it over to the client. Once I do this I could lose access to the site. They can change the login information and they may not need to me manage it. If the client changes anything on the site that compromises my design work, it will reflect my business. My business' name will be on the homepage of the website.

Is this a valid concern?

答: Like others have said, get things in a contract so that you can take your name off it if something happens, etc.  From a business standpoint, I have monetary incentive to host with me (I resell hosting and add value by being a single point of contact for dealing with the actual hosting company I use to provide the hosting service).  The customer is fine if they use their own hosting, but I factor cost in to design/dev projects for keeping track of their login information to make changes, as well as the trouble to figure out the many different tools the various hosting providers have (Godaddy is different from Hostgator is different from Dreamhost is dif...).  So I give my customers a slight discount if they host with me from the start of their website, or, I charge a bit more if I have to work with a client that hosts things themselves.  It's not really enough money to matter, just a few bucks, but does urge them to use my hosting, which is WAY easier for me to manage and control for clients, which lets me give them better, if not more consistent service.  While they have every right to host it wherever they want, this can be a way to try and sway them to go with you, which then also keeps you in their mind when they need to make changes.

Title: Should I allow my client to self host?


答:
Interview Zen online interview engine will let you do this without your presence/time, you can ask the questions and have potential candidates screened before you do a live play by play code review type interview if you feel the need.

How It Works

Define

  Create the set of questions you'd like candidates to answer. Be as creative and job-specific as you like.

Invite

  Invite candidates individually or post the interview link on a job board and let candidates come to you.

Review

  Collaboratively review the recorded interviews in your own time in a shared evaluation space...

Title: Are there any tools for remote coding interview?

Body:
Firstly, I'm not exactly sure if this question is a better fit over here, or on workplace.SE. So forgive me if it is in the wrong place.

We are interviewing some candidates for a development position, and currently they are not in our city.

We would like to give them simple coding tests to see how they will perform on the typical issues that we face in our daily work.

Are there any specific tools geared towards this? Right now we are using Skype and I feel this tends to decrease the performance of a lot of developers since they tend to be shy, and often can't work when someone is directly staring at them.

The problem with sending them the test questions by email are as follows:

It is not possible to know what their thought process is, sine we just see the end result. There is no discussion, or clarification of the question, which is an Important step.

There is no guarantee that the problems were solved by the candidates themselves. They could send it to a smarter friend, and we wouldn't be able to know.

How are these problems usually solved?


问:
Finding maximum number of congruent numbers
Let's say we have a multiset (set with possible duplicates) of integers. We would like to find the size of the largest subset of the multiset such that all numbers in the subset are congruent to each other modulo some m > 1.

For example:

1 4 7 7 8 10

for m = 2 the subsets are: (1, 7, 7) and (4, 8, 10), both having size 3.

for m = 3 the subsets are: (1, 4, 7, 7, 10) and (8), the larger set of size 5.

for m = 4 the subsets are: (1), (4, 8), (7, 7), (10), the largest set of size 2.

At this moment it is evident that the best answer is 5 for m = 3.

Given m we can find the size of the largest subset in linear time.

Because the answer is always equal or larger than half of the size of the set, it is enough to check for values of m upto median of the set.

Also I noticed it is necessary to check for only prime values of m.

However if values in the set are large the algorithm is still rather slow.

Does anyone have any ideas how to improve it?

答:
There may be a way to evaluate the results for several m values with one pass through the multiset - possibly even all of them - though it means deriving another (hopefully smaller) collection of partitions to loop through.

Take the first three m values - as you only need to consider primes, that's 2, 3 and 5. The product of those is 30. So partition the multiset into equivalence classes modulo 30.

Now you can determine the sizes/subsets for m=2, m=3 and m=5 relatively easily. Each m=2 subset consists of every other partition from those 30, each m=3 subset consists of every third partition, and each m=5 subset consists of every fifth partition. With an array of 30 partitions (e.g. linked list heads) to consider, that's much less work than partitioning the whole initial multiset three times. Instead of doing pn classifications, you do n+pq where p is the number of primes for the pass (3 here) and q is the product of those primes (30 for 2, 3 and 5). If n is large enough and q is small enough, this should be a net gain, but q grows rapidly as the number/size of the primes grows.

As q gets larger, it may be possible to reduce the +pq part by tracking which of the modulo values actually occurred in the initial loop - e.g. building a linked list. To be honest, though, I suspect the added complexity would outweigh any gains.

I'm not sure if there's a workable idea in this or not - even if you can build something that works, it's likely that a more complex algorithm will be slower. But maybe there's the core of an idea here.


答:
In Business To Make A Profit

The most common problem I see with freelancers getting caught up in hosting their clients work is they are not turning a profit for it.

ISPs offer hosting solutions based upon the idea that the customer will perform the maintenance of their own website. Most ISPs charge between $75(US) to $95(US) per hour if you need them to do work on the server.

When I speak with freelancers caught hosting their clients work. The majority of the time they collect a small fee (if any at all). That's not the way it should be.

Shared Hosting Paints A Distorted Picture

The majority of small freelance web work can be hosted on shared web solutions. These are either Wordpress sites, small static sites, etc.. etc.. Things that don't require a complex dedicated server.

This has caused the most problems for freelancers.

The average cost for shared hosting is between $10 to $29 per month. This creates a low-perceived value in the eye of the client. They often fail to understand the man hours involved in the maintenance of a website. Shared virus dedicated doesn't really matter. It takes time to set things up, and go in to change things when needed. Getting a Wordpress website to run smoothly has little to do with what kind of service the client rented from the ISPs.

Invest, Grow and Charge For It

You're in business to make money. Run it like a business.

Get yourself a powerful dedicated server that can handle all your customers at once.

Charge your customers an arm and a leg for space on your server.

Put the profits back into investing on better server equipment. Give your customers the best web experience possible.

Buy space on content delivery networks and charge the client for it.

My argument is simple. You have an advantage over other ISPs. The customer is more likely to rent space from you, then having to research and buy space from another company they've never dealt with. It's your chance to mark up, profit and generate another stream of income.

Title: Should I allow my client to self host?

Body:
I'm just starting out as a web designer. I'm trying to build up a portfolio for my own website.

I'm concerned about designing a site and handing it over to the client. Once I do this I could lose access to the site. They can change the login information and they may not need to me manage it. If the client changes anything on the site that compromises my design work, it will reflect my business. My business' name will be on the homepage of the website.

Is this a valid concern?


问:
What needs to change for Software Engineering to become a formal profession?
Unlike other professions (such as Accounting, Law, Medicine, etc.), there is no profession-wide certification for Software Engineering.

I am well aware of the multitude of technology and methodology specific certifications that aim to serve as proof of specialisation and experience, but there is no public Software Engineering society / governing body that sets (and has the power to legally assess) generally accepted professional standards.

I understand that software is a dynamic beast - that is part art, part science - but I'm wondering whether Software Engineering has the potential to become a formal profession.

What needs to change for this to happen, and would it even be a good thing?

(If anybody knows of formal research into this topic I'd greatly appreciate references)

Update

I agree with many of the good points raised below regarding the current level of certification in Software Engineering. I also find it very interesting that some countries treat Software Engineering as a profession whilst others don't.

There does however seem to be a bit of shroud surrounding the term "formal profession", and how it would apply to Software Engineering. I think the key issue with Software Engineering - and the primary reason it is not a full-blown profession - is that if you're a certified Software Engineer, and - for example - some software you wrote for an elevator malfunctions and kills people, your certification and / or membership to a formal professional body won't get revoked.

Sure, your company might get sued for millions, and you personally might lose your job and earn a bad reference, but generally speaking, you personally are protected by the shield of limited liability as a result of being employed by said company. In other words, and as far as I know, there is no legal assessment / enforcement in place (unlike other formal professions and their governing societies) which have the mandate to officially bar you from trading once you've made a colossal stuff-up.

I quite liked the answer that touched on the fact that Software Engineering - as it stands - is a meritocracy, which doesn't need to be a formal profession, and that this is a good thing that shouldn't change. At the same time, I think we need to make a clear distinction between Software Engineers of mission-critical software versus developers of miscellaneous / non-critical software.

To those of you who work / have worked on mission-critical software - is there any personal liability? Surely there is a need for formal repercussions in the event of the Software Engineer making a costly mistake?

答:
I think it should be possible to become a certified software developer by passing an exam the way a lawyer passes a bar exam. I also think that non-certified programmers should still be able to operate as programmers. The difference is that employers would be able to advertise specifically for certified programmers if that's what they want, and a certified programmer would come with certain guarantees of accountability, as well as a higher price tag.

I agree with the poster who says that software development is a buggy mess with no accountability. I don't think it has to be that way. There are developers who want to make good software and are willing to be accountable for it. We just need a way to distinguish ourselves.

I have been developing software for more than 20 years. I don't claim this makes me a great developer by itself, but I do think I'm a pretty good developer. The problem is that I have to constantly demonstrate why I'm a better developer than every kid who learned programming in his spare time and wants the same job as me. Not to mention the legions of "offshore" developers who promise to do the same job for a fraction of the money. Right now this takes a lot of effort. I have to provide work samples, references, take tests, do interviews. I could easily have a bad day, make a mistake on a test, and get disqualified. I'd rather just say, "yes, I'm a certified developer and here is my certificate". I'd still have to do interviews, but at least I'd only be competing against other certified developers.


问:
What are the boundaries of the product owner in scrum?
In another question, I asked about why I feel scrum turns active developers into passive developers, and it seems that the overall problem is not scrumy (related to scrum), and rather it's related to the bad implementation of scrum. So, here I have some questions about the scope of the responsibilities of PO (product owner) and the limitations he/she shouldn't pass.

Should PO interfere the UI design, when there are designers at work in scrum team? (an example of this which has happened to us, is to replace checkboxes with a drop down list with two items, namely, yes and no; or to make some boxes larger, or to left-align some content instead of centering them on the page, or stuff like that). If yeah, to what extent? Colors? Layout?

Should PO interfere in Design and architecture of coding? This hasn't happened to us yet, but I'm really curious about the boundaries. For example does PO has the right to change the platform (moving from ASP.NET MVC to PHP, or something like that), or choosing the count of servers (tier architecture), etc.

Should PO interfere in validation mechanisms? For example, this field should be required, or we don't need to get this piece of information from user. Sometimes, analyzers and designers confirm that something can be handled behind the scene, like extracting the user profile info from another source, instead of asking for it in UI.

How granular could/should PO get into the analysis and design? For example, a user story might be: "As a customer, I'd like to be able to buy new domains online". However, scrum team can implement this user story in a wizard of five steps, or in one single page. To which level PO should monitor, or govern, or supervise the technical analysis, design, and implementation?

I asked these questions to judge whether our implementation is right or wrong?

答:
There is an excellent comment to one of the answers to the question you referred to which I think sums it up nicely. Credit to @StevenV who wrote:

Scrum (as all Agile methodologies) be heavier on conversation than direction. The PO should be describing what the end result needs to be able to accomplish, then engaging the designers and developers on ways to get there. – StevenV Aug 16 '11 at 12:17


问:
How can I send data without POSTFIELDS in PHP curl?
I'm using a REST API through PHP and I'm a bit confused on the CURL_POSTFIELDS behavior, which implies that I must send a querystring or array, but what I'm seeking to do is just to send a string of JSON text.

In the API I'm using there is no such thing as a field: https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Edit+issues

So, how can I just send data that doesn't get interpreted as a query string, and without having to use a file?

答:
I found an article about using JSON with PHP/CURL

In general, we do pretty much this but with an XML-RPC request:

```<code>curl_setopt($cnxn, CURLOPT_POST, TRUE);
curl_setopt($cnxn, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($cnxn, CURLOPT_POSTFIELDS, $body);
</code>```

We just build the XML document for the RPC request into the $body variable, and our server will read it as the request body. We use Zend Framework MVC, but you can read the incoming raw request body from the php://input stream if you're rolling your own.

Body:
I found an article about using JSON with PHP/CURL

In general, we do pretty much this but with an XML-RPC request:

curl_setopt($cnxn, CURLOPT_POST, TRUE);
curl_setopt($cnxn, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($cnxn, CURLOPT_POSTFIELDS, $body);

We just build the XML document for the RPC request into the $body variable, and our server will read it as the request body. We use Zend Framework MVC, but you can read the incoming raw request body from the php://input stream if you're rolling your own.


答:
Turns out all I needed was:

```<code>curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);
</code>```

That way the content sent in the POSTFIELDS gets interpreted the right way. Source: http://www.lornajane.net/posts/2011/posting-json-data-with-php-curl

Title: How can I send data without POSTFIELDS in PHP curl?

Body:
I'm using a REST API through PHP and I'm a bit confused on the CURL_POSTFIELDS behavior, which implies that I must send a querystring or array, but what I'm seeking to do is just to send a string of JSON text.

In the API I'm using there is no such thing as a field: https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Edit+issues

So, how can I just send data that doesn't get interpreted as a query string, and without having to use a file?

Body:
Turns out all I needed was:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);

That way the content sent in the POSTFIELDS gets interpreted the right way. Source: http://www.lornajane.net/posts/2011/posting-json-data-with-php-curl


问:
How to rotate an array of bits

I currently have a PIL Image object which I store as an array of bits (1's and 0's). However I now would like to be able to rotate that image 45 degrees. One way to do it is take the original PIL image, apply a transform matrix on it, then convert that to an array of bits. Problem with this approach is that it's computationally expensive, especially if I want to start doing more than just one rotation. It would be faster to just modify the array of bits directly.

I tried using numpy.roll:

```<code>numpy.roll(bits, 45) # rotate 45 degrees
</code>```

Unfortunately, this just does a circular shift, not an actual angular rotation.

What algorithm can I use on the array of bits to give me the desired output without having to go through the original image? Even though my application is in Python, your answer can be in whatever language you feel comfortable with, I'm more interested in the algorithm itself not the syntax :)

答:
there's no way to do rotation by arbitrary angles without sines and cosines, but it is possible to optimize the calculation depending on what other constraints you're prepared to impose.  This can get very complicated, but can result in huge improvements for the "special case" you've defined.

If your images are all the same size and reasonably small, like your butterfly, and you were planning to do a lot of them, you could preform the slow calculation once, and simply remember the x,y of each pixel of the source image that became the x',y' of the destination image

Title: How to rotate an array of bits


问:
Is it a good idea to read compiler source code?
I'm a junior in college majoring in Computer Science. Apart from writing lots of code, I want to start reading source code written by others to improve my coding skills and learn better/different ways of doing stuff. I was thinking I should start reading some of the key parts of the code in C++ compilers. I think this would help me do two things:

Learn elegant coding practices because compilers are hard and the code represents solutions to this hard problem.

This would also help me learn about how my most used language is compiled, the details, how each error is generated, how code is parsed, and become really good with the specifications of the language.

Do you think this is a good idea?

答:
Hard to say from your post how much you already know about C++, but I wouldn't start by reading a compiler's code. I would spend time with good books first. A very short list:

Programming Pearls (Jon Bentley)

Code Complete (Steve McConnell)

Accelerated C++ (Andrew Koenig and Barbara Moo)

Effective C++ (Scott Meyers)

Design Patterns (Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides)


问:
Does your company have a coding standard?
I recently saw that Microsoft released a coding standards document (All-In-One Code Framework Coding Standards) and it got me thinking...  The company that I work for has no formal coding standards at all.  There are only a few developers and we have been together long enough to have evolved into similar styles and its never been an issue.

Does the company you work for have a documented coding standards?  If no, why not?  Does having a standard make a difference?  Is it worth writing a standard from scratch or should you adopt another standard as your own (ie. make Microsoft's standards yours)?

答:
We're a blub shop, so we use the blub programming conventions.

Now Paul Graham and friends are much smarter than us, but us blub programmers, we can all read each others blub, in fact, any blub programmer can read our blub code.

In fact, because of the design of blub, any blub programmer can read any single blub file and understand it, because blub hasn't got a macro system.

If we program in say, C or C++ (we're all multilingual, even though we program in blub) we use mostly blub style for new code, or for open source stuff, the standard of the project we're working in.


答: If you always want to rotate an image by a specific angle each time, you only need to do the heavy math once (and really, it's not that heavy). The best way to do this is by working the process backwards. For every pixel in the destination image, you calculate the corresponding location in the starting image. This "source" pixel coordinate is saved in what is called a Lookup Table or LUT. Once you build this LUT for the angle and origin of location that you want, then it is very quick to use each entry of the LUT to "move" the pixels of a source image to the correct pixel of the destination image. Where this gets tricky and involves more math is whn deciding how to weight the source date to come up with the destination data. When you work backwards from the integer destination image coordinates, you will end up with floating point coordinates in the source image. These floating point coordinates need to be interpolated. The simplest method is to use the "Nearest Neighbor" integer pixel coordinate to the calculated floating point values, but there are other algorithms such as "Bi-Linear" or "Bi-Cubic" that will provide a better quality of the finished image (but are of course slower than Nearest NEighbor"</p>

Title: How to rotate an array of bits

Body:
I currently have a PIL Image object which I store as an array of bits (1's and 0's). However I now would like to be able to rotate that image 45 degrees. One way to do it is take the original PIL image, apply a transform matrix on it, then convert that to an array of bits. Problem with this approach is that it's computationally expensive, especially if I want to start doing more than just one rotation. It would be faster to just modify the array of bits directly.

I tried using numpy.roll:

```<code>numpy.roll(bits, 45) # rotate 45 degrees
</code>```

Unfortunately, this just does a circular shift, not an actual angular rotation.

What algorithm can I use on the array of bits to give me the desired output without having to go through the original image? Even though my application is in Python, your answer can be in whatever language you feel comfortable with, I'm more interested in the algorithm itself not the syntax :)


答:
Do you think this is a good idea?

The only reason it might be a good idea is so you can get the experience to know that most code, even frequently used, "good" code (especially frequently used, good code in fact) is thoroughly inelegant.

Oh, and it should prove a good learning experience about how code rarely looks like specifications and/or how little code actually follows specifications.

And perhaps so you can learn how much you have to learn.

But no, I don't think this is a good idea - even for the reasons you might gain from it (and definitely not for the reasons you think you might gain from it).

Title: Is it a good idea to read compiler source code?

Body:
I'm a junior in college majoring in Computer Science. Apart from writing lots of code, I want to start reading source code written by others to improve my coding skills and learn better/different ways of doing stuff. I was thinking I should start reading some of the key parts of the code in C++ compilers. I think this would help me do two things:

Learn elegant coding practices because compilers are hard and the code represents solutions to this hard problem.

This would also help me learn about how my most used language is compiled, the details, how each error is generated, how code is parsed, and become really good with the specifications of the language.

Do you think this is a good idea?


问:
What does 'enumerable' mean?
My background in mathematics is very poor (i.e. last relevant math class taken was high school Trigonometry two years ago - another story for another time). I'm reading 'Javascript: The Definitive Guide' and it's a term that is being repetitively used and I've sort of just ran with it. But I've come to a chapter (Chapter 6 - Objects) where my lack of understanding of the term and its application in programming/OOP is starting to become detrimental to the learning process. The online dictionaries aren't helping out, so does somebody have a more explainable definition and/or example to show?</p>

答:
An enumerable is an object that may be enumerated. "Enumerated" means to count off the members of a set/collection/category one by one (usually in order, usually by name).

An enumerable then is an object that can step through a series of other objects one by one.

Title: What does 'enumerable' mean?


答:
I just pulled out my copy of JavaScript: The Definitive Guide, flipped to chapter 6, and quickly read over the section 6.5 Enumeratng Properties. Now, I should add that I'm not a particularly strong math person either, so hopefully this makes sense:

Specifically, "enumerable" means that there is some sort of ordering scheme taking place, so that you can quickly/easily address the items in that set/sequence/collection (or, in that section of JavaScript: The Definitive Guide, the object).

To apply it to what you are reading in the book, when the author says that the properties you extend a class with are enumerable, he is merely saying, that any property you add to an object (not those that are inherited) can be iterated over. So, if you create an object obj like so:

```<code>var obj = {a: 1, b: 2, c: 3};
</code>```

...when you iterate over it with the following loop (I am using descriptive variable names here):

```<code>for (prop in obj) {
    console.log(prop);
}
</code>```

...you will see three items logged to your JS console:

a

b

c

This is telling you that the properties in object obj, are enumerated by the keys a, b, and c.

Title: What does 'enumerable' mean?

Body: My background in mathematics is very poor (i.e. last relevant math class taken was high school Trigonometry two years ago - another story for another time). I'm reading 'Javascript: The Definitive Guide' and it's a term that is being repetitively used and I've sort of just ran with it. But I've come to a chapter (Chapter 6 - Objects) where my lack of understanding of the term and its application in programming/OOP is starting to become detrimental to the learning process. The online dictionaries aren't helping out, so does somebody have a more explainable definition and/or example to show?</p>

Body:
I just pulled out my copy of JavaScript: The Definitive Guide, flipped to chapter 6, and quickly read over the section 6.5 Enumeratng Properties. Now, I should add that I'm not a particularly strong math person either, so hopefully this makes sense:

Specifically, "enumerable" means that there is some sort of ordering scheme taking place, so that you can quickly/easily address the items in that set/sequence/collection (or, in that section of JavaScript: The Definitive Guide, the object).

To apply it to what you are reading in the book, when the author says that the properties you extend a class with are enumerable, he is merely saying, that any property you add to an object (not those that are inherited) can be iterated over. So, if you create an object obj like so:

var obj = {a: 1, b: 2, c: 3};

...when you iterate over it with the following loop (I am using descriptive variable names here):

for (prop in obj) {
    console.log(prop);
}

...you will see three items logged to your JS console:

a

b

c

This is telling you that the properties in object obj, are enumerated by the keys a, b, and c.


答:
I would not start by reading compiler code because it's real complex. You should do a search for C++ projects on(to read the code, build the project, making changes):

```<code>wwww.github.com
www.codeplex.com
code.google.com
</code>```

Also you should read: The C++ Programming Language by Bjarne Stroustrup

Body:
I would not start by reading compiler code because it's real complex. You should do a search for C++ projects on(to read the code, build the project, making changes):

wwww.github.com
www.codeplex.com
code.google.com

Also you should read: The C++ Programming Language by Bjarne Stroustrup


答:
Instead of reading source code, which will likely contain no comments. You should try reading some books on how to write good C++.

Give Scott Meyer's Books a try. I think you'll like his Effective C++ books.


答:
Mathematically, enumerable means "can be placed into a one to one correspondence with the natural numbers". Most representations in computing are enumerable because they are made of strings of bits, and strings of bits can be taken to denote numbers in the binary system.

Some data representations are not considered enumerable, though. For instance a floating point number is made out of bits, but we work with it as an approximation to a real number. At the binary level we can "count" through consecutive floating-point numbers, but usually this is not relevant in numeric applications.

In some other situations, enumeration is possible, but there is no agreement on an enumeration. For instance, all the objects in your run-time image constitute a finite set and can be enumerated. The garbage collector does that that when it walks through the live objects. But the application does not enumerate the set of all objects in that way without regard for type or module boundaries; it enumerates smaller of objects that are of the same kind, or related.

Usually where an enumeration exists formally, there is agreement by all parties. Here is a set of values. This one is first. That one is its successor, and so on.

In some programming languages, there exist enumerated types: some disciplined way of defining named symbolic constants which are mapped by the compiler to unique integer values. If such types are strongly typed, then these constants can only be stored in variables of their corresponding type, called an enumerated type. For instance a user-defined enumeration of type month can only take on the values january through december. These are reduced to the values 0 through 11, and may allow arithmetic, such as successor(january) producing february, or the possibility of using the enumeration as an array index: defining an array days[january..december] where days[january] is, say, 31.   The purpose of an enumerated type, therefore, is to serve as a subset of the natural numbers, by other names that are distinct and provide clarity of meaning (names are used instead of numeric constants) and type checking: the color red from a color enumeration cannot be assigned to a month type enumeration.

The verb enumerate is also used to denote the concept of querying an API to retrieve a list of objects, usually in stepwise fashion: enumerate the network interfaces, enumerate the files in a directory, and so on.  Whenever an object is in a 1:N correspondence with some other objects, it it is susceptible to supporting an enumeration API which lets us walk through those sibling objects, or retrieve them as a list.  The terminology is a little murky; for instance in some cases, even if the elements are not in a particular order, but can all be visited without repetition, it is still enumeration. Some dynamic set data structures such as hash tables do not provide a particular order, and can reorganize themselves as they grown and shrink, so that the actual order varies when insertions and deletions are performed. A can come before B, but when we insert C, now B happens to come before A because some internal reorganization took place.

Title: What does 'enumerable' mean?


答:
No, it's not a good idea because you gain so little. It's better to take the compiler class and read the dragon book if you want to specialise in compiler. If you want to specialise in C++, buy and read the standard. Those will give you more engineering skills than reverse engineering a compiler.

For pure programming skill, I'd recommend "The Practice of Programming" by Pike and Kernighan.


问:
Class structure/pattern for validating several different Excel templates?
I'm trying to validate the contents of Excel sheets that follow several different templates.  For each one, there are three possible validation actions for various cells:

Regex (e.g. "XYZ-123" fails because it doesn't fit pattern "[A-Z]{4}-\d{3}")

Date/Time format (e.g. "Jan 24, 2013" fails because it's not mm/dd/yyyy)

Data type (e.g. "xyz" fails because it's not an integer)

My first thought was to use the following class:

```<code>public class Validator
{
 Excel.Worksheet vSheet;
 List<Tuple<string,string,string>> cellActions=new List<Tuple<string,string,string>>();

 //populates the list of cellActions based on the template type
 public Validator(Excel.Worksheet sht)
 {
  this.vSheet=sht;
  string templateType=templateCheck(sht);
  switch (templateType)
  {
   case "type1":
    cellActions.Add(new Tuple<string,string,string>("C5","regex","[A-Z\d]{6}");
    cellActions.Add(new Tuple<string,string,string>("D3","datatype","long");
    //and so on for another 30 list items
    break;
   case "type2"
    cellActions.Add(new Tuple<string,string,string>("A3","date_time","yyyy-MM-dd HH:mm");
    cellActions.Add(new Tuple<string,string,string>("A6","regex",".+\s[ACGT]{3}");
    //etc.
  }
 }

 private string templateCheck(Excel.Worksheet sht)
 {
  //return template type as string based on contents of worksheet
 }

 public void validate()
 {
  foreach(Tuple<string,string,string> cellAction in cellActions)
  {
   //check the contents of the cell in the vSheet property according to cellAction's rules
  }
 }
}
</code>```

}

Is this a case where Strategy Pattern would be appropriate?  There are several different types of sheets, each with a different list of cells and rules for those cells, so maybe it would be right to think about each template as a strategy to be implemented as a class.  Or is this not a situation where the pattern applies, given that each of the 3 validation action types is always the same regardless of which template it's applied in?

答:
Think about what problem you're trying to solve, and where it might change.  If this is a case of using Excel for users to submit data, you really should consider XML data-binding and an XSD.  (Or, at least, Excel's built-in rules for validation.)

For the specific question, no, I don't think a Strategy pattern is appropriate here.  You're performing the same task, just with a different input each time, and having too-tight binding between your C# program code and the particular standards that happen to be.

Remove the standard rules to a data store of some kind (XML, SQL, flat-file, even an XSL), and load them as you would any other set of data to be tested.  Unless you are using those values and data-structures in code, you shouldn't bind them so tightly.  And with 30+ tests per type of input, it smells like something that will change more often that you suspect.


问:
How do I collect a list of rss feeds?
I am developing a rss reader where users search and follow blogs. But, how will I collect and store the feeds of thousands of blogs?

Manual process of adding individual feeds is painful. Is there an easier way to add or import site feeds?

答:
Don't brute force it.  Include a feature (off by default or with a prompt) to send RSS feeds they add your way.  The same central server that your RSS reader would contact to get a corrected list of feeds (such as when feed X changes its URL) can have an interface to share new feeds.

Just be sure to have your system include some handshake value as well to ward off spam, and be sure not to test the RSS feeds automatically so you're not liable to help someone's DDOS attack.

Title: How do I collect a list of rss feeds?


问:
Deploy PHP project without giving away the source code?
I am working on developing range of web based software solutions. But the problem is that for some clients we need to deploy the applications in their local intranet. In such a situation I have to stick with Java as development language as I cannot give away the source code of the project.

Now in order to tap on more consumers we put these solutions online. Now considering the fact that Java hosting is more expensive than PHP we are left with no choice but to again re develop the entire solution in PHP. Thus we end up having two version of same solution for maintenance and upgrading in different platforms.

So can any point us to some good solution in which we can have the online solution and also have a deployable version of the application in which we can ship the application without its source code and at the same time we also need the application to be cost effective from hosting point of view?

答: My company creates a product - a network appliance with PHP software encrypted using SourceGuardian.  Our customers aren't really into hacking, so we're not worried about them decrypting it.  For the average client, this might work out for you - but they need to be using a hosting environment that allows for the source-guardian service to run (or have it already included by the hosting service - many of them support IonCube).</p>


问:
Javascript behavior depends only on browser or browser + OS?
Generally for a javascript application, compatibility is mentioned in terms of browser types and browser versions it supports.

Frameworks/Libraries like ExtJs also mention about the browser versions they are compatible with.

Does this mean that if my javascript application can run on Google Chrome 10+ version, then any operating system where Google Chrome 10+ can be installed will be able to run my javascript application without any glitches?

Or does type of operating system also have an effect on Javascript execution?

The reason behind asking this is to evaluate the scope of testing of javascript applications before making any commitment to the end user.

Thanks in advance for any guidance provided.

答:
In theory, yes, everything should work fine. In reality, no. The differences should be relatively minor, but they do exist.

As an example, a few years ago I found that some code of mine worked on Safari for windows but not for Mac.

Guidance? Test everything and then test again! Don't trust emulators either. Test on the actual hardware.


问:
Idea of the binary search main theorem
This link really provided some insights into the idea that binary search implications into the optimization problems by giving the main theorem. I am not really confident that I get the idea of the main theorem suggested there. Are there any easy explanations, for the ideas, expressed in that tutorial?</p>

答:
The main requirement for binary search to work is that the array has to be sorted.
Basically, the "main theorem" generalizes that requirement as needed for the generalized binary search on functions instead of arrays. From the article:

Behind the cryptic mathematics I am really stating that if you had a yes or no question (the predicate), getting a yes answer for some potential solution x means that you'd also get a yes answer for any element after x. Similarly, if you got a no answer, you'd get a no answer for any element before x. As a consequence, if you were to ask the question for each element in the search space (in order), you would get a series of no answers followed by a series of yes answers.

Title: Idea of the binary search main theorem


答:
The general environment where JavaScript code is executed is JavaScript engine of your browser.

Nowadays (unlike the first years of JavaScript, where things were not as standardized as it is today) has a standard established by the Ecma International, so the developers are trying to follow this standard. In theory, all browsers covering specific version of the specification should behave in the same way!

But things are not so great when you use external libraries. You probably noticed that in most cases, these libraries have a dependency! They are often depend from the implementation of different technologies such as CSS3, HTML5, etc.

For example, you want to achieve fadeIn effect with jQuery. How it works? For a short period of time, opacity property for specific element is changed - dependency of CSS3's opacity property.

It's the same with some of HTML5 features, they still do not work well enough in all browsers, but here again no problems come from the JavaScript engine, and from the way different HTML5 APIs are implemented in browsers.

Title: Javascript behavior depends only on browser or browser + OS?

Body:
Generally for a javascript application, compatibility is mentioned in terms of browser types and browser versions it supports.

Frameworks/Libraries like ExtJs also mention about the browser versions they are compatible with.

Does this mean that if my javascript application can run on Google Chrome 10+ version, then any operating system where Google Chrome 10+ can be installed will be able to run my javascript application without any glitches?

Or does type of operating system also have an effect on Javascript execution?

The reason behind asking this is to evaluate the scope of testing of javascript applications before making any commitment to the end user.

Thanks in advance for any guidance provided.


答:
Why are you so afraid of letting your customers look at your sourcecode?

When you are afraid of them stealing your code and reselling it, you can easily protect yourself from that through the license agreement.

When you are afraid that they might do simple support changes themself and thus cut you out of your consulting and support business, add a clause to the contract that they must not do any modifications themself and when they do they won't get any more support from you.

Are you afraid that they might steal your "trade secrets"? When your software is really doing something which is so revolutionary that others can't replicate it without seeing your sourcecode, patent it. When it isn't worth patenting, it very likely isn't worth stealing either.

Or are you afraid that the quality of your code will not be up to the customers expectations? Improving your code quality should be in your own interest anyway, no matter who sees it.

On the other hand, giving the customer your sourcecode (even when with heavy licensing shackles) also has advantages you can use as a selling point:

It shows the customer that you trust them

It shows the customer that they can trust you that there are no hidden backdoors in your software

It makes it easier for customers to troubleshoot problems themself before contacting you, giving you more meaningful bug reports

Title: Deploy PHP project without giving away the source code?

Body:
I am working on developing range of web based software solutions. But the problem is that for some clients we need to deploy the applications in their local intranet. In such a situation I have to stick with Java as development language as I cannot give away the source code of the project.

Now in order to tap on more consumers we put these solutions online. Now considering the fact that Java hosting is more expensive than PHP we are left with no choice but to again re develop the entire solution in PHP. Thus we end up having two version of same solution for maintenance and upgrading in different platforms.

So can any point us to some good solution in which we can have the online solution and also have a deployable version of the application in which we can ship the application without its source code and at the same time we also need the application to be cost effective from hosting point of view?


答:
I have experience deploying a similar solution, hosting it in-house and on-premises. For in-house hosting you ofcourse run the code as-is, and for on-premises deployment I've used PHP encoder products (ionCube and Zend Guard).

They are both pretty much equivalent. For this product we only switched to Zend Guard because we standardized our on-premises deployment on Zend Server which comes with Zend Guard Loader support out of the box.

Some thoughts on these solutions:

You have to install the loader extension on the machine where you do hosting, so this may be a dealbreaker for cheap hosting scenarios where you have no control over the server.

PHP version support always lags behind. Zend Guard just a few weeks ago shipped a version that supports 5.4, and 5.5 is right around the corner.

There are bugs every now and then specific to the encoded version, especially when using esoteric features (e.g. on PHP 5.2 we couldn't use reflection to fetch docblock comments in zend guard). It's not a big deal, but it is something to be aware of.

There are compatibility issues with some other extensions, notably xdebug. Again, not necessarily a big deal but something to be aware of.

There is no performance impact that I could tell.

These solutions have built-in support for licensing using license keys. You should check out the abilities if you're interested in that sort of stuff.


问:
Does this violate the using exceptions for flow control "rule"?
I plan to make use of this interface in a plug-in architecture.

```<code>/// <summary>
/// Generic interface allowing you to react to an event.
/// You can block the event or just use it for notification.
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IEventObserver<in T> where T : class
{
    /// <summary>
    /// Throw an exception in here if you want to prevent the event firing.
    /// </summary>
    /// <param name="o"></param>
    void CanFireEvent(T o);

    /// <summary>
    /// This is only called if no handler threw an event in the CanFire.
    /// </summary>
    /// <param name="o"></param>
    void OnBeforeEvent(T o);

    /// <summary>
    /// This is called after the event has happened.
    /// </summary>
    /// <param name="o"></param>
    void OnAfterEvent(T o);
}
</code>```

Example usage:

```<code>public interface ISendMessageObserver : IEventObserver<SendMessageEventArgs>
{
}
</code>```

A plug-in can then implement ISendMessageObserver and prevent message sending by throwing an exception in the CanFireEvent method. However, I know that exceptions should not be used for normal program flow control, yet it is normal and expected for plugins here to stop the flow. I went for this because I'd like the plugin to provide a reason for blocking the event that can be logged or presented to the user.

I could change CanFireEvent to:

```<code>bool CanFireEvent(T o, ref message);
</code>```

or:

```<code>SomeTypeContainingAbortReason CanFireEvent(T o);
</code>```

But both of those don't smell ideal either.

So what do people think, exceptions for flow control OK in this instance?

Edit

I've separated the CanFire into it's own interface and renamed it as PreviewEvent.

```<code>/// <summary>
/// Generic interface allowing you to react to and block an event.
/// </summary>
/// <typeparam name="TArgs"></typeparam>
/// <typeparam name="TBlock"></typeparam>
public interface IEventPreviewer<in TArgs, out TBlock>
    where TArgs : class
    where TBlock : class, IEventBlock
{
    /// <summary>
    /// Return an IEventBlock to prevent the event from firing.
    /// </summary>
    /// <param name="args"></param>
    TBlock PreviewEvent(TArgs args);
}

public interface IEventBlock
{
    string BlockReason { get; }
}
</code>```

答:
No, exceptions are never the right tool for normal flow control. Exceptions should only be used to indicate that a function/method can't fulfil its contract due to external reasons.

In the case of your CanFireEvent method, the function name clearly suggests a yes/no answer and thus a boolean return value, but the second alternative (where the 'No' gets elaborated with a fixed reason also fits.

If I were to have such a function in my event system, I would definitely not allow a free-format reason to be given. What use is it to see the reason "Because I can."

Come to that, allowing plug-ins to prevent messages from being sent makes for an extremely brittle system. You only need one plug-in that consistently blocks all messages to break the whole system.
You could have a bool CanHandleEvent(T) method, with which the plug-in can indicate it it can do something useful with the event, but having a CanFireEvent is just too broad. And most event systems don't even have the CanHandleEvent, they just expect you to be able to handle events at all times (where handling can be that you ignore it).

Update

Based on the comments, I see that the described event mechanism isn't as generic as I thought and that blocking events does not have the meaning "this event can't be handled now", but rather "the proposed action is not valid according to the business rules". That changes the last part of my answer a bit.

If business rules can affect the validity of an action, and this can't be easily determined beforehand, then I would introduce an interface in the system along the lines of

```<code>public interface IActionValidator<in T> // or IEventValidator if you prefer
where T : class
{
    bool IsActionValid(T o, ref message);
}
</code>```

I have separated this from the interface for actually handling the action, as I can imagine that the two are implemented in separate classes/components.

Body:
No, exceptions are never the right tool for normal flow control. Exceptions should only be used to indicate that a function/method can't fulfil its contract due to external reasons.

In the case of your CanFireEvent method, the function name clearly suggests a yes/no answer and thus a boolean return value, but the second alternative (where the 'No' gets elaborated with a fixed reason also fits.

If I were to have such a function in my event system, I would definitely not allow a free-format reason to be given. What use is it to see the reason "Because I can."

Come to that, allowing plug-ins to prevent messages from being sent makes for an extremely brittle system. You only need one plug-in that consistently blocks all messages to break the whole system.
You could have a bool CanHandleEvent(T) method, with which the plug-in can indicate it it can do something useful with the event, but having a CanFireEvent is just too broad. And most event systems don't even have the CanHandleEvent, they just expect you to be able to handle events at all times (where handling can be that you ignore it).

Update

Based on the comments, I see that the described event mechanism isn't as generic as I thought and that blocking events does not have the meaning "this event can't be handled now", but rather "the proposed action is not valid according to the business rules". That changes the last part of my answer a bit.

If business rules can affect the validity of an action, and this can't be easily determined beforehand, then I would introduce an interface in the system along the lines of

public interface IActionValidator<in T> // or IEventValidator if you prefer
where T : class
{
    bool IsActionValid(T o, ref message);
}

I have separated this from the interface for actually handling the action, as I can imagine that the two are implemented in separate classes/components.


问:
Best github repository layout for snippets in multiple programming languages
I have to create a github-presence for an open-source organization. The aim is to distribute code snippets and reference implementations in different programming languages.

These contributions are going to be (ideally) created by people outside of the organization and should be collected.

I know that good practice is to create one repository per project. To this end, each implementation (in a specific programming language) should be considered a standalone project and should get its own repository. The point is that this approach makes hard for external people to contribute, because github pull-requests can only be made against existing repositories.

By creating a single repository with a subdirectory per programming language code contribution becomes easier, but I'm afraid that some IDEs may complain about the directory layout.

I'd like to know whether someone already solved this very specific problem in a satisfactory way.

答:
Thanks for the proposals, they helped us a lot to find a good compromise.

Here is what we came up with:

Since the code snippets are just tiny parts of code, that probably could
not work by themselves, this repository may be shared across languages.

Reference implementations, on the contrary, are likely to be
self-contained and in this case it makes more sense to have a single
repository per each language.

In my opinion the use case for the code snippets is "clone and study":
the snippets should be used for inspiration and small tests, hence I
think it's acceptable to go and look your language of choice. In most
cases people will just look it up on the github website, I guess.

The use case of the reference implementation is "clone and run". I
expect a reference implementation something that I clone in my IDE and
start extending. In this case having a repository per language is of
great help.

I think it's a good compromise also because I expect the reference
implementations to be much less wrt the code snippets, hence the effort
of following the corresponding source repos is not that high.

In case you are interested, the github organization is alpinebits: a definition of an interface, based on OTA and fitted to the Alpine Tourism, for the exchange of touristic data.


问:
Architecture For Mockable DAL On Large Projects
I have recently been reading an article about creating a blog using ASP.NET and MVC, and in the article the user splits the Data Access Layer into a separate Class Library, and creates an interface for this to allow the DAL to be mocked for testing.

This works great for small projects, but I am struggling to see how this will scale. For example in the article you end up with the following Interface:

```<code>public interface IBlogRepository
{
    IList<Objects.Post> Posts(int pageNo, int pageSize);
    int TotalPosts(bool checkIsPublished = true);

    IList<Objects.Post> PostsForCategory(string categorySlug, int pageNo, int pageSize);
    int TotalPostsForCategory(string categorySlug);
    Objects.Category Category(string categorySlug);

    IList<Objects.Post> PostsForTag(string tagSlug, int pageNo, int pageSize);
    int TotalPostsForTag(string tagSlug);
    Objects.Tag Tag(string tagSlug);

    IList<Objects.Post> PostsForSearch(string search, int pageNo, int pageSize);
    int TotalPostsForSearch(string search);

    Objects.Post Post(int year, int month, string titleSlug);

    IList<Objects.Category> Categories();
    IList<Objects.Tag> Tags();

    IList<Objects.Post> Posts(int pageNo, int pageSize, string sortColumn, bool sortByAscending);

    void AddPost(Objects.Post post);
}
</code>```

There is then an associated .cs file with the implementation of this interface.

How would you implement a similar architecture for a much larger project? For example the project I have at work consists of 25 controllers, each having as a minimum list, add, edit, view, delete and count. That would lead to an interface with 150+ functions.

Is this kind of architecture still suitable for larger projects, and if so how would you structure this to avoid having a single file implementing 150+ functions?

答:
Take a look at using a generic base repository that contains some of the common functionality between all repositories.

```<code>interface IRepository<T>
{
     void Save();
     T GetById(int id);
     int GetCount();
}
</code>```

From this you can create custom repositories for each action.

```<code>interface IUserRepository : IRepository<UserPosts>
{
    UserPosts GetPostsByUserId(int userId);
}

interface IOtherRepository : IRepository<OtherObject>
{
    void OtherRepositoryAction(int id);
}
</code>```

This way you can reduce the number of actions each individual repository has. It also saves having a single "God" repository that does all actions for the application.

Strategies for creating repositories include:

One per database table

One per aggregate route

For the aggregate route model take a look at Domain Driven Design. Eric Evans  has an excellent book on Domain Driven Design.

For each repository that you create you should apply dependency injection to bind the interface to a concrete type. DI containers include:

Autofac

StructureMap

Ninject

Depending on your architecture, these repositories can be called as follows (NOTE: I am not saying this is the best way, but it is a way):

```<code>public class UserController: Controller
{
    private readonly IUserService _userService;
    UserController(IUserService userService)
    {
         _userService = userService;
    }
    public void SaveUser(User user)
    {
        _userService.SaveUser(user);
    }
}

public UserService : IUserService
{
     private readonly IUserRepository _userRepository;
     public UserService(IUserRepository userRepository)
     {
        _userRepository = userRepository;
     }
     public void SaveUser(User user)
     {
         _userRepository.Save(user);
     }
}
</code>```

Body:
Take a look at using a generic base repository that contains some of the common functionality between all repositories.

interface IRepository<T>
{
     void Save();
     T GetById(int id);
     int GetCount();
}

From this you can create custom repositories for each action.

interface IUserRepository : IRepository<UserPosts>
{
    UserPosts GetPostsByUserId(int userId);
}

interface IOtherRepository : IRepository<OtherObject>
{
    void OtherRepositoryAction(int id);
}

This way you can reduce the number of actions each individual repository has. It also saves having a single "God" repository that does all actions for the application.

Strategies for creating repositories include:

One per database table

One per aggregate route

For the aggregate route model take a look at Domain Driven Design. Eric Evans  has an excellent book on Domain Driven Design.

For each repository that you create you should apply dependency injection to bind the interface to a concrete type. DI containers include:

Autofac

StructureMap

Ninject

Depending on your architecture, these repositories can be called as follows (NOTE: I am not saying this is the best way, but it is a way):

public class UserController: Controller
{
    private readonly IUserService _userService;
    UserController(IUserService userService)
    {
         _userService = userService;
    }
    public void SaveUser(User user)
    {
        _userService.SaveUser(user);
    }
}

public UserService : IUserService
{
     private readonly IUserRepository _userRepository;
     public UserService(IUserRepository userRepository)
     {
        _userRepository = userRepository;
     }
     public void SaveUser(User user)
     {
         _userRepository.Save(user);
     }
}


问:
Is there a time bomb in sequential process id allocation when the `unsigned` wraps?
I'm designing and implementing a multiprocessing postscript interpreter ("lightweight" processes simulated by a single OS-thread), and I need to generate a unique identifier for each process in the system, as well as maintain ids for any dead processes which still have live references. (Reference: Adobe PLRM, 2ed, Ch. 7 Display PostScript, http://partners.adobe.com/public/developer/en/ps/psrefman.pdf)

I've started with a simple increment, which arithmetically maps to the table index for the per-process data.

http://code.google.com/p/xpost/source/browse/itp.c#115

```<code>unsigned nextid = 0;  // global (file-static) counter

unsigned initctxid(void) {  // generate a new cid
    while ( ctxcid(++nextid)->state != 0 )  // .state == 0 means free
        ;
    return nextid;
}

context *ctxcid(unsigned cid) {  // get context data from cid
    return &itpdata.ctab[ (cid-1) % MAXCONTEXT ];
}
</code>```

But there's gonna be a big problem if (when) the unsigned wraps around. Perhaps not scary for a game or an application, but this thing is supposed to be a server. Eventually. I'd like to avoid writing (in earnest) the disclaimer, "warning: will start having strange problems after running for a long time".

So, it should be easy enough to detect when it wraps, but what then? Bail out?

So the situation/scenario so far is: you're a multitasking postscript server with a handful of processes with cids allocated during one epoch of the generator, and the epoch has just turned. My thought (not impossible, just seems really hard) is to compact these existing IDs down to the 0..N range (rewriting all references, scanning all memory if necessary) and reset nextid to N.

But that's gonna be a pain-in-the-butt. Is there a different way to generate these IDs so I don't have to do a big garbage-collect on them, and have it work, you know, perpetually?

Edit: A fact I neglected to mention was that the Display PostScript reference says IDs are not re-used during a running instance of the system. But since these IDs are not exposed, they cannot be saved in any form other than the context object. So re-use should be just fine as long as no running process can know about it (contains an old context object in accessible memory).

答:
It doesn't matter if nextid wraps (as long as you don't have any overflow checking enabled).

What will happen is that the id is just passed into the function ctxcid which limits it to the range [0..MAXCONTEXT) (using the mod %). So the wrapping around happens way before the nextid wraps around.

So actually the worse case for you is the array filling up, which will cause an infinite loop because that while loop won't exit.


问:
Efficient way to shuffle objects
I'm writing a program for some quiz software. I have a question class containing the ArrayLists for the question, answer, options, marks and negative marks. Something like this:

```<code>class question
{
    private ArrayList<Integer> index_list;
    private ArrayList<String> question_list;
    private ArrayList<String> answer_list;
    private ArrayList<String> opt1_list;
    private ArrayList<String> opt2_list;
}
</code>```

I want to shuffle all questions, but for questions to be shuffled, all the objects need to be shuffled. I would have approached this problem in this way:

First of all, I would not have used this design and used String not ArrayList<String> type as instance variables, and would then have used the Collections.shuffle method to shuffle objects. But my team insists on this design.

Now, the question class is containing increasing ArrayLists as the entry to the questions are made. How to shuffle the questions now?

答:
Your team suffers from a common problem: object denial.

Instead of a class that holds a single question with all the information associated with it, you try to create a class called question that holds all the questions in a single instance.

That's the wrong way to go about it, and it complicates what you try to do a lot! Sorting (and shuffling) parallel arrays (or Lists) is nasty business and there's no common API for it, simply because you usually want to avoid it at all.

I suggest you restructure your code like this:

```<code>class Question
{
    private Integer index;
    private String question;
    private String answer;
    private String opt1;
    private String opt2;
}

// somewhere else
List<Question> questionList = new ArrayList<Question>();
</code>```

This way, shuffling your question becomes trivial (using Collections.shuffle()):

```<code>Collections.shuffle(questionList);
</code>```

Title: Efficient way to shuffle objects

Body:
Your team suffers from a common problem: object denial.

Instead of a class that holds a single question with all the information associated with it, you try to create a class called question that holds all the questions in a single instance.

That's the wrong way to go about it, and it complicates what you try to do a lot! Sorting (and shuffling) parallel arrays (or Lists) is nasty business and there's no common API for it, simply because you usually want to avoid it at all.

I suggest you restructure your code like this:

class Question
{
    private Integer index;
    private String question;
    private String answer;
    private String opt1;
    private String opt2;
}

// somewhere else
List<Question> questionList = new ArrayList<Question>();

This way, shuffling your question becomes trivial (using Collections.shuffle()):

Collections.shuffle(questionList);


问:
Anemic Domain Model vs. DDD by definition example(s)?
What is an example of "Business Logic" that should reside in the DomainModel i.e. inside an Entity instead of inside a (Domain) Service, as well as some example logic that should be in a service.

Here are what I would consider to be pretty clear cases(?):

Basic Validation would be done by the ViewModel definition attributes and jQuery validation. Therefore data correctness should be fine by the time data gets to the Service/DomainModel(Entity).

Some business logic that depends on other Entities would belong somewhere outside the Entity in a service (naturally/presumably).

Something that I could picture existing in a DomainModel (Entity) would be simple adding items to a list property (ensure no duplicates exist etc.). Perhaps some basic copy functionality.

What else do you put in the Entity/DomainModel, instead of the Service? It's hard to make a clear distinction, or at least it feels like most of the logic would end up in the Service(s).

答: Domain model is usually (and I assume in your case really) normal object model. So same rules and practices apply to domain modelling as for object modelling. So I would look at SOLID, KISS, and various design patterns.</p>


答:
You don't. You make another list/queue of indexes and shuffle that. Then you iterate down the indexes which drive the "shuffled" order of your other collections.

Even outside of your scenario with things split apart, the separate ordering collection provides a number of benefits (parallelism, speed when reseating the original collection is costly, etc).

Title: Efficient way to shuffle objects

Body:
I'm writing a program for some quiz software. I have a question class containing the ArrayLists for the question, answer, options, marks and negative marks. Something like this:

```<code>class question
{
    private ArrayList<Integer> index_list;
    private ArrayList<String> question_list;
    private ArrayList<String> answer_list;
    private ArrayList<String> opt1_list;
    private ArrayList<String> opt2_list;
}
</code>```

I want to shuffle all questions, but for questions to be shuffled, all the objects need to be shuffled. I would have approached this problem in this way:

First of all, I would not have used this design and used String not ArrayList<String> type as instance variables, and would then have used the Collections.shuffle method to shuffle objects. But my team insists on this design.

Now, the question class is containing increasing ArrayLists as the entry to the questions are made. How to shuffle the questions now?


答:
Create a class Question2:

```<code>class Question2
{
    public Integer index_list;
    public String question_list;
    public String answer_list;
    public String opt1_list;
    public String opt2_list;
}
</code>```

Then create a function mapping a question to ArrayList<Question2>, use Collection.Shuffle for that result, and create a second function for mapping ArrayList<Question2> back to question.

Afterwards, go to your team and try to convince them that using an ArrayList<Question2> instead of question would improve their code a lot, since it would save them a lot of that unnecessary conversions.

Title: Efficient way to shuffle objects

Body:
Create a class Question2:

class Question2
{
    public Integer index_list;
    public String question_list;
    public String answer_list;
    public String opt1_list;
    public String opt2_list;
}

Then create a function mapping a question to ArrayList<Question2>, use Collection.Shuffle for that result, and create a second function for mapping ArrayList<Question2> back to question.

Afterwards, go to your team and try to convince them that using an ArrayList<Question2> instead of question would improve their code a lot, since it would save them a lot of that unnecessary conversions.


问:
Does giving a developer a slower development machine result in faster/more efficient code?
Suppose I give my developers a screaming fast machine.  WPF-based VS2010 loads very quickly.  The developer then creates a WPF or WPF/e application that runs fine on his box, but much slower in the real world.

This question has two parts...

1) If I give a developer a slower machine, does that mean that the resulting code may be faster or more efficient?

2) What can I do to give my developers a fast IDE experience, while giving 'typical' runtime experiences?

Update:

For the record, I'm preparing my even-handed response to management. This isn't my idea, and you folks are helping me correct the misguided requests of my client.  Thanks for giving me more ammunition, and references to where and when to approach this.  I've +1'ed valid use cases such as:

- specific server side programming optimizations

- test labs

- the possibly buying a better server instead of top of the line graphics cards

答:
Boy I'll get clobbered for this, but there's something people don't want to hear:

Nature abhors a vacuum.

Of course programmers want faster machines (me included), and some will threaten to quit if they don't get it. However:

If there's more cycles to be taken, then they get taken.

If there's more disk or RAM to fill up, it gets filled up.

If the compiler can compile more code in the same time, then more code will be given to it.

If it is assumed that the extra cycles, storage, and code all serve to further gratify the end user, one may be permitted to doubt.

As far as performance tuning goes, just as people put in logic bugs when they program, they also put in performance bugs.
The difference is, they take out the logic bugs, but not the performance bugs, if their machine is so fast they don't notice.

So, there can be happy users, or happy developers, but it's hard to have both.


问:
Should I bother to develop for JavaScript disabled?
Should I bother to develop for JavaScript disabled?

I feel that my time is better spent developing for the majority.

答:
Depends on the answer to a single question:

"Is the cost of supporting users with Javascript disabled greater than or less than the money lost by not supporting those users?"

Say your website has a lifespan of 3 years before needing to be rebuilt, it costs £30,000 to build for 'rich clients', and you add another £10,000 to support non-javascript users (of which we'll assume there are 5% of)

If the missing 5% of users would have spent more than £10,000 - do it. If they wouldn't, don't do it unless you're legally required to.

This is more of a business/economical decision than a technical one.


答: It depends very much on your target market.  If your target market is non-techs, you're pretty safe ignoring javascript disabled.  However, if you're after techies, well, the majority of the ones I know have javascript disabled...  You're going to need to support them unless you want the small portion of techies that allows javascript (I'm one of the minority, I let javascript run on my machines).  :-)</p>

Body:
Should I bother to develop for JavaScript disabled?

I feel that my time is better spent developing for the majority.


答:
I agree with the other answers that the correct solution is to use a proper object model.

However, it is actually quite easy to shuffle multiple lists in identical manner:

```<code>Random rnd = new Random();
long seed = rnd.nextLong();

rnd.setSeed(seed);
Collections.shuffle(index_list, rnd);
rnd.setSeed(seed);
Collections.shuffle(question_list, rnd);
rnd.setSeed(seed);
Collections.shuffle(answer_list, rnd);
...
</code>```

Title: Efficient way to shuffle objects

Body:
I agree with the other answers that the correct solution is to use a proper object model.

However, it is actually quite easy to shuffle multiple lists in identical manner:

Random rnd = new Random();
long seed = rnd.nextLong();

rnd.setSeed(seed);
Collections.shuffle(index_list, rnd);
rnd.setSeed(seed);
Collections.shuffle(question_list, rnd);
rnd.setSeed(seed);
Collections.shuffle(answer_list, rnd);
...


答:
There have been several discussions about all this.

Have a look at this SE question where Iulian Margarintescu said something pretty interesting:

[...] the anemic domain model is not by itself an anti-pattern, only when
  you try to do DDD and end up with and anemic model.

He mentioned this pretty interesting article as well.

From my own experience, when I work with generated EF POCOs (Anemic Domain Model) I tend to put my business rules into specifications. That way I’m able to write business rules for any of my domain entities and chain them while querying.

EDIT:

If you want to follow DDD strictly, please read this. Eric Evans is describing what exactly should be the role of a service and what should be put in it.

Title: Anemic Domain Model vs. DDD by definition example(s)?

Body:
What is an example of "Business Logic" that should reside in the DomainModel i.e. inside an Entity instead of inside a (Domain) Service, as well as some example logic that should be in a service.

Here are what I would consider to be pretty clear cases(?):

Basic Validation would be done by the ViewModel definition attributes and jQuery validation. Therefore data correctness should be fine by the time data gets to the Service/DomainModel(Entity).

Some business logic that depends on other Entities would belong somewhere outside the Entity in a service (naturally/presumably).

Something that I could picture existing in a DomainModel (Entity) would be simple adding items to a list property (ensure no duplicates exist etc.). Perhaps some basic copy functionality.

What else do you put in the Entity/DomainModel, instead of the Service? It's hard to make a clear distinction, or at least it feels like most of the logic would end up in the Service(s).


问:
Appropriate License for Available-Source, No-Unauthorized-Distribution
I have a program (technically an addon to a program) whose code I want to be freely available for educational purposes or to create derivatives for personal use. However, I do NOT want to allow unregulated redistribution of either modified or unmodified code, whether for free or for profit.

However, I do want to allow the possibility of "pre-approved" derivative works - that is, the ability for a developer to request permission to distribute a derivative work (essentially an addon to an addon).

Finally, the licensing for the parent program (which I do not own) forbids selling my addon directly but does not forbid monetization via other means (such as adfly). I do not want to allow others to monetize my original code, but do want to allow them to monetize pre-approved derivative works.

Because of the rather nuanced nature of these requirements, and the fact it is NOT a free-distribution license like would be required for a "true" Open-Source license (as per the official definition), I do not know what license to use. Would creating my own be the best choice? Note that I do not have a lawyer nor do I have the resources to obtain one.

It appears on its face to be closest to a "visible source" license, but those do not seem to accommodate the "approved derivative work" aspect I want.

Here is the license as I have it so far. Is this a valid format and are these terms permitted to be used in this manner?

```<code>    /*******************************************************************************
    * @author Reika
    *
    * This code is the property of and owned and copyrighted by Reika.
    *
    * Any and all users are permitted to use the source for educational purposes, or to create derivative works
    * for private use only.
    *
    * Unless given explicit written permission - electronic writing is acceptable - no user may redistribute this
    * source code nor any derivative works. These pre-approved works must prominently contain this copyright notice.
    *
    * Additionally, no attempt may be made to achieve monetary gain from this code by anyone except the original author.
    * In the case of pre-approved derivative works, any monetary gains made will be shared between the original author
    * and the other developer(s), proportional to the ratio of derived to original code.
    *
    * Finally, any and all displays, duplicates or derivatives of this code must be prominently marked as such, and must contain
    * attribution to the original author, including a link to the original source. Any attempts to claim credit for
    * this code will be treated as intentional theft.
    *
    * Due to the Mojang and Minecraft Mod Terms of Service and Licensing Restrictions, compiled versions of this code
    * must be provided for free. However, with the exception of pre-approved derivative works, only the original author
    * may distribute compiled binary versions of this code.
    *
    * Failure to comply with these restrictions is a violation of copyright law and will be dealt with accordingly.
    ******************************************************************************/
</code>```

答:
Licences are legal documents and thus you should ask a lawyer if your license covers what you want.

In my, non-lawyer, opinion, you try to cover too much in your license text. Most of it applies only to those persons that have gotten explicit permission from you to distribute the software, so you can just handle that in the 'contract' with which you give them the permission to distribute.

In my view, an appropriate license in your case could be:

```<code>/*********************
 * @author Reika
 * Copyright 2013
 *
 * All rights reserved.
 * Distribution of the software in any form is only allowed with
 * explicit, prior permission from the owner.
 *
 */
</code>```

When people ask you for that permission, you are free to attach whatever conditions you want, such as attribution and that it can't be sold for money.
You can even use different restrictions for different people.

Body:
Licences are legal documents and thus you should ask a lawyer if your license covers what you want.

In my, non-lawyer, opinion, you try to cover too much in your license text. Most of it applies only to those persons that have gotten explicit permission from you to distribute the software, so you can just handle that in the 'contract' with which you give them the permission to distribute.

In my view, an appropriate license in your case could be:

/*********************
 * @author Reika
 * Copyright 2013
 *
 * All rights reserved.
 * Distribution of the software in any form is only allowed with
 * explicit, prior permission from the owner.
 *
 */

When people ask you for that permission, you are free to attach whatever conditions you want, such as attribution and that it can't be sold for money.
You can even use different restrictions for different people.


问:
What is the best way to load balance javascript applications?
I write a lot of javascript applications and in many different circumstances the browser will become unresponsive or give a "slow script" error. Even when following best practices, initializing large data sets, complex animation, or when too many event handlers fire at once, I have to include extra setTimeouts or requestAnimationFrames around script blocks to load balance them. Seems like there should be some standard way of managing the browser load for large javascript applications.

Any ideas? It seems like there must be JS application designers thinking about this, but I can find nothing on the web or on stack.

edit

I appreciate all the response. My question is not "How can I write efficient Javascript?" which seems to be the question the current responses are answering. My question is: How can I balance the load of multiple sequential threads of javascripts running in the same browser?

I am well aware of all the information posted in the responses so far and appreciate the posters, but I am looking for a framework or a design pattern that balances script execution in a browser. This question is common in many other languages and for devops, I am simply asking the same question for javascript.

答:
So based on your edits I read this as asking "how do I effectively divide up a long running calculation into multiple web workers." I've been writing a library for dealing with web workers and here's what I found, there are a couple different ways you can do this which often depend on the data.  Assuming you have a array that you want to process using n workers.

You can just arbitrarily split up the array in n parts and send a part to each worker. Either through slicing the array (if it's small) or by iterating through the list and sending each chunk of data to a different worker (via Math.random() or %).  If your data items take a fairly uniform amount of time to process this is going to be as fast as a queue but isn't going to have the overhead.

You can set up a queue so that after processing a piece of data the worker sends the result back and gets the next piece. This will balance the load pretty well and means that if one piece of data takes 500ms and the rest takes 1ms you won't have of data waiting behind the 500ms piece.  But you now have workers waiting to get their data and other added complexity that can lead to slower times then the first queue types, but also faster in others, especially if you use transferable objects to speed up transfer times.

You can just do it one worker.  This isn't actually a solution to the question you asked, but could be a solution to the problem you have, I find it's really a good idea to double check that the overhead of dividing your data up into multiple parts doesn't outweigh the benefits you get. Especially considering that since Chrome doesn't support workers making more workers you have to do the dividing up in the DOM thread.


问:
DDD/SOA in (.NET) MVC and Message pattern(s) / Request Response
We're currently considering whether it makes sense (or if the benefits are worth the added code) to introduce a Message based pattern (such as Request Response) into a Domain Driven Design / Service Oriented Architecture under an MVC app (with DI and potentially used by MVC, WCF, Windows Services, etc.).

Basically (in MVC) the controller uses an injected service which in turn uses an injected repository to save/update/delete objects.

There are Application Services, and Domain Services and the application service might use multiple domain services to e.g. save something and then send an email about the item being saved.

Considering the example use case where something is saved and then an email is sent, it could be useful to present any potential errors to the user such as "Save succeeded, but the email wasn't able to be sent. Please try again in 5 minutes or contact support etc." vs just a generic error such as "Save or email didn't succeed".

The message based pattern with Request and Response objects seems fine (in theory), or at least the response objects with e.g. a couple inherited fields could be useful.

```<code>public abstract class ResponseBase
{
    public bool Success { get; set; }
    public string Message { get; set; }
}
</code>```

Then there could be an object to extend it with the ViewModel result as a property and finally the controller could decide whether to show e.g. an error message, or update the view etc.

This seems nice, but in the simple cases where you are simply saving an item and it's clear the save succeeded or failed, it can also seem to be overkill. Creating and passing extra objects where maybe you just need an ID and a Boolean seems to make this pattern redundant. The thing is that this object needs to transfer from the controller, through the services, down to the repository, and back. The request part could be possible to ignore and only worry about returning a meaningful result too.

It's hard to estimate whether it could be 50-50 or 40-60 where this type of system could be useful, but there are many cases that could use it, as well as many that aren't very useful.

Is there better approaches to this issue, or have you found this pattern useful for the scenario portrayed? Is it worth the extra coding for the simple cases (in your case(s))?

答:
Another option would be to throw custom exception in your domain service as soon as something go wrong and catch it, preferably, in your model builder. That way your actual code is still valid, but rather having to pass some sort of extra objects just to deal with error messages, you just throw an exception and catch it at the right place. Of course, keep on handling all unhandled exceptions (things that are not supposed to happen) in the Application_Error method as you probably do right now.

Here’s an example:

```<code>public ActionResult Deposit(DepositModel model)
{
 // Some code...

 try
 {
  var depositResult = _cardDepositService.Perform(someParmaeters);

  // Some more checks...

  // The deposit has succeeded
  return DepositSuccess(model.Amount.DepositAmount.Value);
 }
 catch (DepositAmountException ex)
 {
  this.SetPopupMessage(ErrorMsg.DepositAmountError);
  return PartialView("DepositPanel", model);
 }
}
</code>```

There are several ways to handle errors in MVC apps, feel free to manage them your way ;-)

Hope that helps!

Body:
Another option would be to throw custom exception in your domain service as soon as something go wrong and catch it, preferably, in your model builder. That way your actual code is still valid, but rather having to pass some sort of extra objects just to deal with error messages, you just throw an exception and catch it at the right place. Of course, keep on handling all unhandled exceptions (things that are not supposed to happen) in the Application_Error method as you probably do right now.

Here’s an example:

public ActionResult Deposit(DepositModel model)
{
 // Some code...

 try
 {
  var depositResult = _cardDepositService.Perform(someParmaeters);

  // Some more checks...

  // The deposit has succeeded
  return DepositSuccess(model.Amount.DepositAmount.Value);
 }
 catch (DepositAmountException ex)
 {
  this.SetPopupMessage(ErrorMsg.DepositAmountError);
  return PartialView("DepositPanel", model);
 }
}

There are several ways to handle errors in MVC apps, feel free to manage them your way ;-)

Hope that helps!