问:
How can I learn about typography, fonts, glyphs, etc.?
I know so little about this that I'm having trouble formulating the question.

Apparently due to technical limitations, nastaleeq style of writing Urdu is very difficult, perhaps impossible, given current standards used on the web. I'd like to do a deep dive into why this is so (the technical aspects, at least).

My, very rough, understanding is this:

Unicode is the standard right now, but it doesn't define how characters look, it only define the names of characters and a numbering system to represent them.

"Fonts," such as Halvetica or Times New Roman, actually define the look of characters.

What is True Type then, and how is it different from Open Type or Postscript or LaTex?

If a language requires that shapes of characters, and how the connect to each other (think cursive), change, based on their location in text...how is that handled? If Unicode is only a representation system and fonts only concern themselves with single characters, where do these location based algorithms go?

Is the current set of standards too limited to handle complex cursive style typography? If so, can HTML's canvas be used to create an alternative/experimental "font system?" If I do need to "roll my own" is Knuth's work on digital typography still relevant or are there more modern references?

答:
That's a whole bunch of questions, and not all have easy answers.

Easy Answers

Unicode is a language-independent method for encoding strings of text as sequential numbers of a defined data size per-letter, with the most common being UTF-8, which uses eight-bits per character and is largely identical for the old ASCII English-language equivalent.

Fonts are the means of mapping both UTF and ASCII strings to a human-readable graphic.  Both TrueType and OpenType are different standards for defining fonts, with the latter being the more recent.

PostScript and LaTeX are languages that specifically help layout documents for the printed page, rather than encoding strings.  TeX is a foundation to LaTex and PDF is an extension of PostScript, but all are special cases that aren't relevant to the score question aside from being an alternative to HTML or XUI.

How should position-dependent languages be encoded?

Languages where one glyph is substituted for another based on word position should use different glyphs for each variant.  It's how capital letters already work in English-like languages, and those have the same language-specific rules as to when semantically equivalent glyph should be used on top of another.

If the variants can be expressed as combining one symbol over another, they can be entered as ligatures instead of separate glyphs, which allows for both fonts and strings to be smaller and thus faster for computers to render.

Can Nastaleeq be written in UTF-8?

I would suspect not, at least not without tolerating a significant spelling variance.  This puts the language in company of languages where each word is its own glyph, such as Chinese and Japanese.  Assuming there is a usable UTF glyph definition for the alphabet and its various ligatures, that is.

So, is there a UTF standard for Nastaleeq?

It certainly seems as if there is. The external links section of the Nastaleeq Wikipedia page has references to various fonts and software packages that support the script, including links to a web community that opens up in a font that certainly isn't English.  But, as I cannot read Urdu or Nastaleeq, I have no idea if http://www.nastaliqonline.ir/ is displaying actual Nastaleeq or a UTF-8 constrained subset.


问:
Where should user permission checks take place in and MVC and by who?
Should user permission checks take place in the model or the controller? And who should handle the permission checks, the User object or some UserManagement helper?

Where should it happen?

Checking in the Controller:

```<code>class MyController {
  void performSomeAction() {
    if (user.hasRightPermissions()) {
      model.someAction();
    }
  }
  ...
</code>```

Having the checks in the Controller helps making the Models simple actions, so we can keep all logic to the Controllers.

Checking in the Model:

```<code>class MyModel {
  void someAction() {
    if (user.hasRightPermissions()) {
      ...
    }
  }
  ...
</code>```

By putting the checks in the Model, we complicate the Model, but also make sure we don't accidentally allow users to do stuff they aren't supposed to in the Controller.

And by who?

Once we've settled on the place, who should do the checks? The user?

```<code>Class User {
  bool hasPermissions(int permissionMask) {
    ...
  }
  ...
</code>```

But it's not really the user's responsibility to know what he or she can acccess, so perhaps some helper class?

```<code>Class UserManagement {
  bool hasPermissions(User user, int permissionMask) {
    ...
  }
  ...
</code>```

I know it's common to ask just a single question in, well, a question, but I think these can be answered nicely together.

答:
As usual, "it depends"

permission checks will functionally  work anywhere it's convenient to put them,

but if you're asking a technical question then the answer may be 'put the checks in the object that owns the data required to perform the check' (which is probably the controller).

but if you're asking a philosophical question, I suggest an alternate answer: don't show users actions that they are not permitted to perform.

So in the latter case you might have the permission check in the controller implemented as a boolean property, and bind that property to the Visible property of the button or panel in the user-interface that controls the action

as a user, it's frustrating to see buttons for actions that I cannot perform; feels like I'm being left out of the fun ;)

ContentLicense: CC BY-SA 3.0


问:
Business Logic Layer in MVC Application
In my ASP MVC application I decided to add another Business Layer and made the model only to have properties.

All other functionality like save to db, get from db is done on this new Business layer. So now the controller will be calling this business layer and model for various operations. Is it a good approach to design like this?

I decided not to use model for this purpose because I would need a number of models for different actions. (for eg, one for edit and other for create)

答: Certainly an Active Record is a great start, but what about the business logic for integrity (e.g., add an order - that affects the customer's balance).  I would caution about putting that in the client model, since it is not exposed as a service for reuse by other clients, other computers and so forth.  I'd recommend architecting this into a middle tier or database, as I argued  here.

Title: Business Logic Layer in MVC Application


问:
How do you build debugging messages into your programs/scripts?
General, high-level question for people who work with code regularly.

I was repurposing some old, outdated Javascript code into a Chrome extension, and to help me understand it, I wrote some quick code to help (see below). I regularly put messages in my code such as dbmsg('Begin function loadDefaults()'); or dbmsg('Settings saved to storage'); and the message is sent to the console. Whenever I need to debug something where the standard console messages aren't helping, I just turn on debugging. I figure this method is pretty simple and can be ported to other languages.

What other ways do you build debugging into your programs? I'm self-taught, so I don't know the standard practices, but I'm more interested in unique ways you've found to do this sort of thing.

```<code>/** Debugging Tools
 *
 * Set debugMode to 1 to show error messages, 0 to hide messages.
 */
var debugMode = 1;
function dbmsg(message) {
    if ( debugMode == 1 ) {
        var date = new Date();
        var time = date.getHours() + ':'
            + date.getMinutes() + ':'
            + date.getSeconds();
        console.log('DBM - ' + time + ': ' + message);
        if ( chrome.runtime.lastError ) {
            console.log('DBM lastError - ' + chrome.runtime.lastError);
        }
    } else if ( debugMode == 0 ) {
        return;
    }
}
if ( debugMode == 1 ) {
    console.log('Debug mode is currently ON. Each debug message is preceeded with "DBM" and the time the message was generated.');

    // Listen for changes in storage
    chrome.storage.onChanged.addListener(function(changes, namespace) {
        for (key in changes) {
            var storageChange = changes[key];
            dbmsg('Storage key "%s" in namespace "%s" changed. ' +
                  'Old value was "%s", new value is "%s".',
                  key,
                  namespace,
                  storageChange.oldValue,
                  storageChange.newValue);
        }
    });
}
</code>```

答:
Debugging by creating execution traces is a much undervalued technique. It is a valuable tool for the programmers tool kit. Like any tool, it has its area of application; at other times a break point debugger is more useful, or generating a stack trace.

Debugging by traces is most use

when no other debugger is available, for various reasons.

when stopping the program would mess with timers.

when debugging a multithreaded program where you need to see actual interleaving of threads.

when a (subtle) bug develops over a long execution sequence.

The difference is that a break point debugger gives you a snapshot of the program state, and the trace shows what happens over time. Bugs that are hard to solve with one tool can be easier to crack with another tool.

The way to build trace tools varies with the target language. What is constant is the featutes to provide. Here is my list of basic features

Able to be turned on and off by setting a flag. The flag value can be hard-coded or set at run-time by debugging code.

For compiled languages the effect of the debugging code should be able to be completely removed. When turned off the debugging code should have no effect on the program. Debugging code can have bugs too, and always gives a performance hit.

Support a way of logging that a function or method has been entered. The log should contain the filename / class name, the method / function name, and each argument value.

Support a way of logging method or function exit, including return value.

Support for logging an arbitrary message.

Support logging to file or console.

More advanced features include

Indenting each log message according to the call depth.

Prefixing each log message with a date and time stamp.

Support multiple log files where N are retained.

Support for a maximum log file size, either by wrapping to the start or switching to a new file.

Support for logging levels, from none to extremely detailed.

Ability to select logging by source file / class name or feature name.

In C or C++, this can all be achieved with conditional compilation of macros in include files. By setting a compiler flag the macros can be completely turned off without touching the source code, an important ability to have. The code can be much more compact in C++ be because we can take advantage of polymorphism.

In Java, we can implement the debug code in a pair of jar files, one with all the debugging methods implemented, and the other with empty methods. This takes advantage of the JVM's optimisation abilities. Of course Log4J should be considered.

In scripting languages you can mix and match the above techniques to achieve the same effect. For html / javascript you can use the script tag to include the required javascript debugging source. If the page is generated from PHP you can conditionally include the debugging code in the page.

The basic features can be built in about 50 lines of code (as I recall, since I'm not as my desk machine), and the advanced features can be another 100 or so lines.

The function trace features described above can be implemented in Javascript (using your dbmsg function) as (not tested):

```<code>function dbcall( /* name, args */ ) {
  var msg = arguments[0] + '( ';
  for (var i = 1; i < arguments.length - 1; i++)
    msg += arguments[i] + ', ';
  msg += arguments[arguments.length - 1] + ' )';
  dbmsg( msg );
}

function dbretn( /* name, value */ ) {
  var msg = arguments[0] + ' returns ';
  msg += arguments[1];
  dbmsg( msg );
}
</code>```

In a language that supports macros we can set up a macro that calls dbretn that does the return, but in javascript we need to add the call in front of each return as in

```<code>...
dbretn( `MyFunction`, value );
return value;
</code>```

The storage.changed listener you show in the question is a good example of how such debugging facilities should be adapted the each environment.

Body:
Debugging by creating execution traces is a much undervalued technique. It is a valuable tool for the programmers tool kit. Like any tool, it has its area of application; at other times a break point debugger is more useful, or generating a stack trace.

Debugging by traces is most use

when no other debugger is available, for various reasons.

when stopping the program would mess with timers.

when debugging a multithreaded program where you need to see actual interleaving of threads.

when a (subtle) bug develops over a long execution sequence.

The difference is that a break point debugger gives you a snapshot of the program state, and the trace shows what happens over time. Bugs that are hard to solve with one tool can be easier to crack with another tool.

The way to build trace tools varies with the target language. What is constant is the featutes to provide. Here is my list of basic features

Able to be turned on and off by setting a flag. The flag value can be hard-coded or set at run-time by debugging code.

For compiled languages the effect of the debugging code should be able to be completely removed. When turned off the debugging code should have no effect on the program. Debugging code can have bugs too, and always gives a performance hit.

Support a way of logging that a function or method has been entered. The log should contain the filename / class name, the method / function name, and each argument value.

Support a way of logging method or function exit, including return value.

Support for logging an arbitrary message.

Support logging to file or console.

More advanced features include

Indenting each log message according to the call depth.

Prefixing each log message with a date and time stamp.

Support multiple log files where N are retained.

Support for a maximum log file size, either by wrapping to the start or switching to a new file.

Support for logging levels, from none to extremely detailed.

Ability to select logging by source file / class name or feature name.

In C or C++, this can all be achieved with conditional compilation of macros in include files. By setting a compiler flag the macros can be completely turned off without touching the source code, an important ability to have. The code can be much more compact in C++ be because we can take advantage of polymorphism.

In Java, we can implement the debug code in a pair of jar files, one with all the debugging methods implemented, and the other with empty methods. This takes advantage of the JVM's optimisation abilities. Of course Log4J should be considered.

In scripting languages you can mix and match the above techniques to achieve the same effect. For html / javascript you can use the script tag to include the required javascript debugging source. If the page is generated from PHP you can conditionally include the debugging code in the page.

The basic features can be built in about 50 lines of code (as I recall, since I'm not as my desk machine), and the advanced features can be another 100 or so lines.

The function trace features described above can be implemented in Javascript (using your dbmsg function) as (not tested):

function dbcall( /* name, args */ ) {
  var msg = arguments[0] + '( ';
  for (var i = 1; i < arguments.length - 1; i++)
    msg += arguments[i] + ', ';
  msg += arguments[arguments.length - 1] + ' )';
  dbmsg( msg );
}

function dbretn( /* name, value */ ) {
  var msg = arguments[0] + ' returns ';
  msg += arguments[1];
  dbmsg( msg );
}

In a language that supports macros we can set up a macro that calls dbretn that does the return, but in javascript we need to add the call in front of each return as in

...
dbretn( `MyFunction`, value );
return value;

The storage.changed listener you show in the question is a good example of how such debugging facilities should be adapted the each environment.


问:
How would you create useful tests for Oracle BI Publisher reports?
I'm curious about how to test reports that seem rather straightforward. I'm supposed to create test cases for an Oracle report(XML Publisher/BI Publisher). So for example, a report is supposed to just return columns(say , 10 columns).

Here  is what I thought of so far:

```<code>Validate that the  report returns accurate output.
Validate that the all column headers and table values are correctly aligned and there are no run-ons/incorrect formatting
Validate that dates are in the MM/DD/YYYY format
Validate that all currencies are accurate, and contain 2 decimal places.
</code>```

Here's a sample pic(of what the report produces) :

What would the edge/boundary cases be? If the report takes in parameters, does that make it more demanding of a report?

Thanks

答:
If you're writing unit tests, you're creating a program to verify that the target code, given a specific set of input, returns a known and expected output.  To make unit tests for your reports, you need:

A mock database that you run your test reports against.

Sufficient mock data to generate reports.

Known examples of the output said reports should generate when said mock data in mock database is sent.

Unless you're actually working on development of the Oracle software itself, you don't need to test things like "are dates actually dates" or "does each column have a header."  You only need to match your mock input to your mock output, and expand your test suite until you cover all applications needed for usages in production.

OTOH, if you're actually going to test how the report returns items based on your live database, you're writing integration tests and possibly even production checks.  (Are you tests going to run each time the report does, or just when a new version of code is pushed to production?)

In all cases, I'd only test that which is either important to the end-user ("is the sales column actually sales?")  or otherwise part of your design specification ("UserCancellation Report includes only users marked for cancellation.").

Knowing precisely how many tests to write and what to write requires a lot of domain knowledge, not the least of which is how often these tests are ran and what your test framework is like.  (You are using an automated test suite of some kind, either OSS or purchased from a vendor or even home-grown, right?)


问:
Is using static-typing the solution to domain-driven design and decreasing the number of errors?
We are using PHP (a dynamically-typed language) in our project. However, I have found my colleagues asking questions such as https://stackoverflow.com/questions/20438322/modeling-a-binary-relationship-between-two-types.

I’m feeling like we have a paranoia that we are going to get unexpected errors (E.G. if you look at that example question, you will see that the poster is asking how to ensure that a like does not get initialized for a Person), and we are using static-typing (something that doesn't exist in PHP) along with unit tests to help ourselves rest easy at night. :-)

Now, the thing that tells me our approach is wrong is the number of big websites written using dynamically-typed languages: Google uses Python extensively, Facebook is written using PHP, Twitter and GoodReads are written using Ruby. So what I feel is that web applications—at the very least—are moving toward dynamically-typed languages.

However, no matter how I try to comprehend this, i can’t. Don’t these guys have trouble comprehending the domain? Don’t they have problems that arise when using dynamically-typed languages (E.G. “Property whatever is not defined on this object.”)? If they do, how do they deal with those while keeping the agility that comes with using dynamically-typed languages?

答:
You're over-thinking the differences between interpreted and compiled languages, and not really realizing the benefit of dynamic object creation and object oriented design.

Assuming that you had a situation similar to the question linked, where a user could like a Business but not a Person, you would be better off not allowing a direct instantiation of a distinct Like object, but instead making the execution point a method on the Business object.

That is, instead of:

```<code>//Like a business
$thisBiz = ...;
$myLike = new Like[$thisBiz];
</code>```

You could have:

```<code>//Like a business
$thisBiz = ...;
$myLike = $thisBiz.Like();
</code>```

If a latter programmer tries calling a method of an object that doesn't possess it, they'll get a runtime error, and a good IDE will catch it at design-time as well.  Which is exactly what happens in a compiled language with static types.

The real power of dynamic typing is when you want to make a change to how things work.  If Like is an object that takes a business as a parameter, and you want to allow people to be liked as well, you may wind up having to make a second Like constructor, or even a separate class, or even redefine it to accept a Thing parent that both Businesss and Person can be CAST to.  Or you could just add the  method to the Person class and be done with it.

Body:
You're over-thinking the differences between interpreted and compiled languages, and not really realizing the benefit of dynamic object creation and object oriented design.

Assuming that you had a situation similar to the question linked, where a user could like a Business but not a Person, you would be better off not allowing a direct instantiation of a distinct Like object, but instead making the execution point a method on the Business object.

That is, instead of:

//Like a business
$thisBiz = ...;
$myLike = new Like[$thisBiz];

You could have:

//Like a business
$thisBiz = ...;
$myLike = $thisBiz.Like();

If a latter programmer tries calling a method of an object that doesn't possess it, they'll get a runtime error, and a good IDE will catch it at design-time as well.  Which is exactly what happens in a compiled language with static types.

The real power of dynamic typing is when you want to make a change to how things work.  If Like is an object that takes a business as a parameter, and you want to allow people to be liked as well, you may wind up having to make a second Like constructor, or even a separate class, or even redefine it to accept a Thing parent that both Businesss and Person can be CAST to.  Or you could just add the  method to the Person class and be done with it.


答:
As already mentioned MVC is just a presentation pattern and there is nothing wrong in having a business layer. However, you should not call that layer directly from the Controller, as these are supposed to be very thin and without any logic.

There are actually multiple patters that you can, it seesms the Pattern3 mentioned here suits your requirments.

Title: Business Logic Layer in MVC Application

Body:
In my ASP MVC application I decided to add another Business Layer and made the model only to have properties.

All other functionality like save to db, get from db is done on this new Business layer. So now the controller will be calling this business layer and model for various operations. Is it a good approach to design like this?

I decided not to use model for this purpose because I would need a number of models for different actions. (for eg, one for edit and other for create)

ContentLicense: CC BY-SA 4.0


答:
how do they deal with those while keeping the agility that comes with
  using dynamically-typed languages?

Many people would argue if you really want to be agile (i.e. comfortably change your code often), you need unit testing.

Relying on the compiler to make sure: 2+2=Number is really just a false sense of security. So if you're going to take the trouble to write a unit test, why not be a little more accurate and test: 2+2=4?

With Domain Driven Design, you're dealing with much more complicated problems and objects (That's typically why it is used.) that will barely be managed by type checking alone. Consider writing some tests.

Title: Is using static-typing the solution to domain-driven design and decreasing the number of errors?

Body:
We are using PHP (a dynamically-typed language) in our project. However, I have found my colleagues asking questions such as https://stackoverflow.com/questions/20438322/modeling-a-binary-relationship-between-two-types.

I’m feeling like we have a paranoia that we are going to get unexpected errors (E.G. if you look at that example question, you will see that the poster is asking how to ensure that a like does not get initialized for a Person), and we are using static-typing (something that doesn't exist in PHP) along with unit tests to help ourselves rest easy at night. :-)

Now, the thing that tells me our approach is wrong is the number of big websites written using dynamically-typed languages: Google uses Python extensively, Facebook is written using PHP, Twitter and GoodReads are written using Ruby. So what I feel is that web applications—at the very least—are moving toward dynamically-typed languages.

However, no matter how I try to comprehend this, i can’t. Don’t these guys have trouble comprehending the domain? Don’t they have problems that arise when using dynamically-typed languages (E.G. “Property whatever is not defined on this object.”)? If they do, how do they deal with those while keeping the agility that comes with using dynamically-typed languages?


问:
Why Big Data Needs To Be Functional?
I started working on a new project lately related to Big Data for my internship.
My managers recommended to start learning functional programming (They highly recommended Scala).
I had a humbled experience using F#, but I couldn't see the the important of using this paradigm of programming as it's expensive in some cases.

Dean gave an interesting talk about this topic, and shared his thoughts on why "Big Data" here : http://www.youtube.com/watch?v=DFAdLCqDbLQ
But it wasn't very convenient as Big Data doesn't mean only Hadoop.

As BigData is very vague concept. I forget it for a while. I tried to come-up with one simple example to compare between the different aspects when we deal with data, to see if functional way is expensive or no.
If functional programming is expensive and memory-consuming for small data, why do we need it for Big Data ?

Far from fancy tools, I tried to build a solution for one specific and popular problem using three approaches: Imperative way and functional way (recursion, using collections). I compared time and complexity,to compare between the three approaches.

I used Scala to write these functions as it's the best tool to write an algorithm using three paradigms

def main(args: Array[String]) {
    val start = System.currentTimeMillis()
    // Fibonacci_P
    val s = Fibonacci_P(400000000)
    val end = System.currentTimeMillis()
    println("Functional way: \n the Fibonacci sequence whose values do not exceed four million : %d \n Time : %d ".format(s, end - start))
    val start2 = System.currentTimeMillis()

    // Fibonacci_I
    val s2 = Fibonacci_I(40000000 0)
    val end2 = System.currentTimeMillis();
    println("Imperative way: \n the Fibonacci sequence whose values do not exceed four million : %d \n Time : %d ".format(s2, end2 - start2))
}
```

<p>Functional way :     </p>

<pre class="lang-scala prettyprint-override"><code>def Fibonacci_P(max: BigInt): BigInt = {
    //http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Stream
    //lazy val Fibonaccis: Stream[Long] = 0 #:: 1 #:: Fibonaccis.zip(Fibonaccis.tail).map { case (a, b) => a + b }
    lazy val fibs: Stream[BigInt] = BigInt(0)#::BigInt(1)#::fibs.zip(fibs.tail).map {
        n = > n._1 + n._2
    }
    // println(fibs.takeWhile(p => p < max).toList)
    fibs.takeWhile(p = > p < max).foldLeft(BigInt(0))(_ + _)
}
</code>```

Recursive way:

def Fibonacci_R(n: Int): BigInt = n match {
    case 1 | 2 = > 1
    case _ = > Fibonacci_R(n - 1) + Fibonacci_R(n - 2)
}
```

<p>Imperative way:</p>

<pre class="lang-scala prettyprint-override"><code>def Fibonacci_I(max: BigInt): BigInt = {
    var first_element: BigInt = 0
    var second_element: BigInt = 1
    var sum: BigInt = 0

    while (second_element < max) {
        sum += second_element

        second_element = first_element + second_element
        first_element = second_element - first_element
    }

    //Return
    sum
}
</code>```

I noticed that Functional programming is heavy! it takes longer time and consume more space in memory.
I am confused, whenever I read an article or watch a talk, they say that we should use functional programming in data science.
True, it 's easier and more productive, specially in data world. but it takes more time and more memory space .

So, why do we need to use Functional programming in Big Data ?
What are the best practices to use functional programming (Scala) for Big Data ?

答:
I don't know scala and therefore I cannot comment on your functional approach, but your code looks like overkill.

Your recursive function on the other hand is inefficient. Because the function calls itself twice, it is of order 2^n, which is highly inefficient. If you want to compare the three approaches, you need to compare three optimal implementations.

The Fibonacci function can be implemented recursively with calling the function only once. Let's take a more generalized definition :

```<code>F(0) = f0
F(1) = f1
F(n) = F(n-1) + F(n-2)
</code>```

The standard special case is :

```<code>f0 = 0
f1 = 1
</code>```

The general recursive function is :

```<code>function fibonacci($f0, $f1, $n){
    if($n < 0 || !isInt($n)) return false;
    if($n = 0) return $f0;
    if($n = 1) return $f1;
    return fibonacci($f1, $f0 + $f1, $n - 1);
}
</code>```

Title: Why Big Data Needs To Be Functional?

Body:
I don't know scala and therefore I cannot comment on your functional approach, but your code looks like overkill.

Your recursive function on the other hand is inefficient. Because the function calls itself twice, it is of order 2^n, which is highly inefficient. If you want to compare the three approaches, you need to compare three optimal implementations.

The Fibonacci function can be implemented recursively with calling the function only once. Let's take a more generalized definition :

F(0) = f0
F(1) = f1
F(n) = F(n-1) + F(n-2)

The standard special case is :

f0 = 0
f1 = 1

The general recursive function is :

function fibonacci($f0, $f1, $n){
    if($n < 0 || !isInt($n)) return false;
    if($n = 0) return $f0;
    if($n = 1) return $f1;
    return fibonacci($f1, $f0 + $f1, $n - 1);
}


答:
Security is a cross-cutting concern, therefore needs to be implemented in multiple layers. What follows is an example for MVC but the concept applies to other architectures and/or patterns, you just have to identify the points of enforcement.

Where should it happen?

Views might contain UI elements (widgets, buttons, menus etc.) that need to be displayed or not for some users, based on their permissions. This could be a responsibility of the view engine, since you don't want every view to handle this on its own. Depending on the type of elements you're doing authorization on you cold move this responsibility in another place. For example, think of a menu in which some items have to be displayed and some don't. The items can be implemented as a list somewhere and filter that list based on permissions then forward it to the view.

Controllers respond to requests, so if a user doesn't have the permission to execute an action it should be checked before the action is invoked, moving the responsibility to the action invoker instead of keeping it in the controller. This has the advantage of keeping your controller clean and if something changes in the permissions you don't have to sift through your controllers to apply those changes.

Resources are displayed based on permissions. This is normally done at database level, since you don't want to pull everything from the database and then apply permissions.

As you can see, depending on what you want to authorize there are different places where this should be done. The goal is to be as unobtrusive as possible, so that when your security policy changes you can easily apply it, preferably without altering your application's code. This might not be valid for small applications, where the permission set is fairly small and doesn't change very often. In enterprise applications though, the story is quite different.

Who should do it?

Clearly not the model. Each layer should have an enforcement point that handles the authorization. The italic text above highlights the possible enforcement point for each level.

Have a look at XACML. You don't have to implement it as is, but it will give you some directions that you could follow.

Title: Where should user permission checks take place in and MVC and by who?

Body:
Should user permission checks take place in the model or the controller? And who should handle the permission checks, the User object or some UserManagement helper?

Where should it happen?

Checking in the Controller:

```<code>class MyController {
  void performSomeAction() {
    if (user.hasRightPermissions()) {
      model.someAction();
    }
  }
  ...
</code>```

Having the checks in the Controller helps making the Models simple actions, so we can keep all logic to the Controllers.

Checking in the Model:

```<code>class MyModel {
  void someAction() {
    if (user.hasRightPermissions()) {
      ...
    }
  }
  ...
</code>```

By putting the checks in the Model, we complicate the Model, but also make sure we don't accidentally allow users to do stuff they aren't supposed to in the Controller.

And by who?

Once we've settled on the place, who should do the checks? The user?

```<code>Class User {
  bool hasPermissions(int permissionMask) {
    ...
  }
  ...
</code>```

But it's not really the user's responsibility to know what he or she can acccess, so perhaps some helper class?

```<code>Class UserManagement {
  bool hasPermissions(User user, int permissionMask) {
    ...
  }
  ...
</code>```

I know it's common to ask just a single question in, well, a question, but I think these can be answered nicely together.


问:
Python interview questions
I am going to interview within two weeks for an internship that would involve Python programming.

Can anyone suggest what possible areas should I polish? I am looking for commonly asked stuff in interviews for Python openings. Apart from the fact that I have already been doing the language for over a year now, I fail to perceive what they can ask me.

Like for a C or C++ interview, there are lots of questions ranging from reversing of strings to building linked lists, but for a Python interview, I am clueless.

Personal experiences and/ or suggestions are welcomed.

答:
How about something involving Python list comprehensions? To me, those were one of the big selling points over C++, after I read about them in Dive into Python.

"Write a list comprehension that builds a list of the even numbers from 1 to 10 (inclusive)".

Where the answer is anything like this (note the range values avoid a fencepost error):

```<code>foo = [x for x in range(1, 11) if (x % 2) == 0]
print foo
[2, 4, 6, 8, 10]
</code>```

For that matter, if you understand all the concepts listed in Dive into Python, that should cover most of the important features.

OwnerDisplayName: Andy

ContentLicense: CC BY-SA 2.5

Title: Python interview questions

Body:
How about something involving Python list comprehensions? To me, those were one of the big selling points over C++, after I read about them in Dive into Python.

"Write a list comprehension that builds a list of the even numbers from 1 to 10 (inclusive)".

Where the answer is anything like this (note the range values avoid a fencepost error):

foo = [x for x in range(1, 11) if (x % 2) == 0]
print foo
[2, 4, 6, 8, 10]

For that matter, if you understand all the concepts listed in Dive into Python, that should cover most of the important features.


答:
As long as you can run it on a single machine, it's not "Big Data". Your example problem is completely inappropriate to demonstrate anything about it.

Big Data means that the problem sizes are so big that distributing the processing is not an optimization but a fundamental requirement. And functional programming makes it much easier to write correct and efficient distributed code due to immutable data structures and statelessness.

Title: Why Big Data Needs To Be Functional?

Body:
I started working on a new project lately related to Big Data for my internship.
My managers recommended to start learning functional programming (They highly recommended Scala).
I had a humbled experience using F#, but I couldn't see the the important of using this paradigm of programming as it's expensive in some cases.

Dean gave an interesting talk about this topic, and shared his thoughts on why "Big Data" here : http://www.youtube.com/watch?v=DFAdLCqDbLQ
But it wasn't very convenient as Big Data doesn't mean only Hadoop.

As BigData is very vague concept. I forget it for a while. I tried to come-up with one simple example to compare between the different aspects when we deal with data, to see if functional way is expensive or no.
If functional programming is expensive and memory-consuming for small data, why do we need it for Big Data ?

Far from fancy tools, I tried to build a solution for one specific and popular problem using three approaches: Imperative way and functional way (recursion, using collections). I compared time and complexity,to compare between the three approaches.

I used Scala to write these functions as it's the best tool to write an algorithm using three paradigms

def main(args: Array[String]) {
    val start = System.currentTimeMillis()
    // Fibonacci_P
    val s = Fibonacci_P(400000000)
    val end = System.currentTimeMillis()
    println("Functional way: \n the Fibonacci sequence whose values do not exceed four million : %d \n Time : %d ".format(s, end - start))
    val start2 = System.currentTimeMillis()

    // Fibonacci_I
    val s2 = Fibonacci_I(40000000 0)
    val end2 = System.currentTimeMillis();
    println("Imperative way: \n the Fibonacci sequence whose values do not exceed four million : %d \n Time : %d ".format(s2, end2 - start2))
}
```

<p>Functional way :     </p>

<pre class="lang-scala prettyprint-override"><code>def Fibonacci_P(max: BigInt): BigInt = {
    //http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Stream
    //lazy val Fibonaccis: Stream[Long] = 0 #:: 1 #:: Fibonaccis.zip(Fibonaccis.tail).map { case (a, b) => a + b }
    lazy val fibs: Stream[BigInt] = BigInt(0)#::BigInt(1)#::fibs.zip(fibs.tail).map {
        n = > n._1 + n._2
    }
    // println(fibs.takeWhile(p => p < max).toList)
    fibs.takeWhile(p = > p < max).foldLeft(BigInt(0))(_ + _)
}
</code>```

Recursive way:

def Fibonacci_R(n: Int): BigInt = n match {
    case 1 | 2 = > 1
    case _ = > Fibonacci_R(n - 1) + Fibonacci_R(n - 2)
}
```

<p>Imperative way:</p>

<pre class="lang-scala prettyprint-override"><code>def Fibonacci_I(max: BigInt): BigInt = {
    var first_element: BigInt = 0
    var second_element: BigInt = 1
    var sum: BigInt = 0

    while (second_element < max) {
        sum += second_element

        second_element = first_element + second_element
        first_element = second_element - first_element
    }

    //Return
    sum
}
</code>```

I noticed that Functional programming is heavy! it takes longer time and consume more space in memory.
I am confused, whenever I read an article or watch a talk, they say that we should use functional programming in data science.
True, it 's easier and more productive, specially in data world. but it takes more time and more memory space .

So, why do we need to use Functional programming in Big Data ?
What are the best practices to use functional programming (Scala) for Big Data ?


问:
Finding patterns in logs
I am trying to put together a way to figure out if incidents occurred based on log content. Typically, on log (or DB table) would contain a list of transactions composed as follow:
{Timestamp} {TransactionID} {Message}

As an example problem I have run into, I used this to detect if "incidents" occured by running some very basic queries such as:

```<code>SELECT Timestamp, count(*)
FROM table
GROUP BY Timestamp
HAVING COUNT(*) > 5
ORDER BY Timestamp
</code>```

This works OK but has very strong caveats:

In times of high activity it will return records for nothing (and raising the bar will hide rows that should get returned)

Let say I have 4 events at timestamp t and 2 events at timestamp (t+1), my query will not return anything even if they should be considered. Unfortunately, aggregating timestamps by time ranges will lead me to the previous point about high activity time.

Would someone have some insights on how to tackle the broader problem of incident detection within logs?

答:
Your query is currently trying to detect incidents by the heuristic "many log events happened in a short window of time".  For some classes of "incidents", this might be a good heuristic, but it sounds like it isn't for you.  I don't know what you mean by "incident" in this context, but I assume you are trying to detect trouble on a server or something, but the

A better approach is to put more information in to the log.  What information that should be will be specific to your problem domain.  As an example, one way to add more information is to add an {event type} column to your data.  Then you might have event types like "purchase successful" or "ERROR" or "transaction cancelled by user" or "search found no results", or whatever list of types defines the kind of events you are trying to notice.  Then your queries can be structured to include that, and your heuristic can be improved or perhaps become a deterministic algorithm.

In general, deciding what to log and how to log it is a function of what questions you want to ask the logs.  It's about what you need out of them.  So if you start from that perspective, and then design your logging, it will be a lot easier to answer those questions when you need to.

Title: Finding patterns in logs


问:
A metric to measure the cost of cut and paste programming
I'm hunting a metric to measure the cost of cut-and-paste programming. We already use tools to detect duplicated code - but if we don't clean up our duplicated code, how much will it cost us?

We know that the DRY principle, Don't Repeat Yourself, is a core principle of Extreme Programming. How can we actually measure the impact of non-DRY code on our projects?

I'm referring to the simplest duped code problem of the same expressions in two or more places. Other cases of duplication such as the same logic written differently in different places is trickier to detect.

I'm hunting a metric, a solid number that I can offer management. I am aware of the "WTF" metric of Robert Martin, but that is not precise enough.

What is the purpose of insisting on a metric? Management is insisting on this metric and they won't be dissuaded. I'm really afraid that they may mandate that duplicated code be reduced on each sprint. Because we are so pressed to deliver, developers will find the duplicated code and hack it so it does not get detected. This would be a ticking time bomb!

答:
So I was going to comment, instead of answer, but then I decided I wished to be a little more verbose.

Management insisting on reduced duplication in each sprint?  Sign me up!  I am usually fighting with them to allow us to spend time doing things like that, reducing technical debt sprint by sprint rather than simply piling it all up for some kind of bug-stomping fest, or god forbid, a massive production issue later!

You said sprint, so I am going to make a few assumptions here.  I am a Certified Scrum Master, for what that may or may not be worth to you.  So, Sprint: 1) you are using SCRUM or a similar framework. 2) You have planning meetings for each sprint, and commit to work in these planning meetings, after estimating it as a team.

You say you are pressed for time.  Do you have an overall deadline that MUST happen, regardless of the team's commitment each sprint and how much they can deliver?  If not, then when you estimate your stories at each sprint planning, try to take into account the cost of doing it 'right', IE not duplicating the logic in question, and instead wrapping it in some form of pattern that will make it reusable.  Not only will you make management happy, but you will make yourselves happier as well!  No more changing multiple copies of things when a business rule changes.  No more wondering what where you have to go to find where you did it before, instead its part of an ongoing centralized library of tools at your disposal.

The key is: Nothing is free.  If you have significant duplication (and I would say you do if even the management is seeing it as a problem), then explain that it takes time to fix that.  The only way you have the time to fix it correctly is if they back off a bit on the time schedules, and let you do it.  If you have control over commitment (you as in the developers) then commit to what you can do, realistically, and properly!  If you don't have control over comitting to work (I have been there.) then talk to the PO or whomever DOES control the roadmap and release dating and explain the situation, the likely problems from not fixing it, and get them to agree.

If all of that fails, and management insists on duplication being reduced, but doesn't also guarantee the extra time that is needed to do it, you are between a rock and a hard place.  The only thing the developer in me has for that is 'take the time you need to do it right'.  I have never ever ever been reprimanded, by even my most unreasonable managers, for being late but getting it done right, over getting it done on time but having it blow up in a customers face.  Sounds like now is the time to regroup and talk about it though, regardless.

OwnerDisplayName: JC.


答:
Two problems here.

One is the total lack of any reliable metrics. Lines of Code can be measured accurately -- but is a meaningless and unusable figure, Total Cost of Ownership is meaningful and useful but can only be measured after the patient is dead.

Second. Re-factoring and reducing repetition that has crept into your could base is a real cost now. Any costs associated with maintaining a bloated code base (and if its well tested with stable requirements these costs may be zero) belong in the future and, probably, to another manager.

While you should strive to avoid writing the same code again and again (if only to save wear and tear on the keyboard) once its there you are pretty much stuck with it. Its almost always the right management decision to favor working and tested code over "pretty" code.

Title: A metric to measure the cost of cut and paste programming

Body:
I'm hunting a metric to measure the cost of cut-and-paste programming. We already use tools to detect duplicated code - but if we don't clean up our duplicated code, how much will it cost us?

We know that the DRY principle, Don't Repeat Yourself, is a core principle of Extreme Programming. How can we actually measure the impact of non-DRY code on our projects?

I'm referring to the simplest duped code problem of the same expressions in two or more places. Other cases of duplication such as the same logic written differently in different places is trickier to detect.

I'm hunting a metric, a solid number that I can offer management. I am aware of the "WTF" metric of Robert Martin, but that is not precise enough.

What is the purpose of insisting on a metric? Management is insisting on this metric and they won't be dissuaded. I'm really afraid that they may mandate that duplicated code be reduced on each sprint. Because we are so pressed to deliver, developers will find the duplicated code and hack it so it does not get detected. This would be a ticking time bomb!

OwnerDisplayName: James Anderson


答:
Duplicated costs extra effort to understand, to maintain (e.g., modifying the duplicates), and to find (you can't fix the duplicates if you don't know where they are).

I have experience building duplicate code detection tools (see bio).  My tool has found 10-20% duplication (sometimes a LOT more) in pretty much every big system it is pointed at.  This means every programmer is looking at 10-20% more code than is technically necessary.

If you believe programmers spend 50% of their time just looking at code, and 10-20% of that is unnecessary, then some 5-10% of a programmer's time is wasted by the existence of cloned code.  If your programmer costs $100K burdened, that  $5K-$10 per year per programmer.  If have 10 programmers, that's $50-100K/year of wasted engineering costs and corresponding delay in delivery of useful results.

Clone detection tools seem pretty valuable from this point of view.  It does take effort to make the clones go away, so the savings from having a clone detection isn't quite as high.

OTOH, it is really hard to find a software engineering metric that suggests you can get any obvious percentage improvement by doing things differently.  (Software Reuse arguably delivers 20-30% improvement). Clone detection/removal is up there pretty high in general.

YMMV.

OwnerDisplayName: Ira Baxter


答:
Prediction of the future is always difficult and I am not aware of any precise formula to calculate the cost of code clones. What we do in our code quality audits is that we calculate the clone overhead by putting the size of the system in relation to the size of a hypothetical variant of the system without any clones. That allows you estimate how much time or money you could save if there were less clones. But please note that this is just a very rough estimation and I think it's way not precise enough to be used for defining any quality goals.

The question remains of how to calculate the size of the redundancy-free system. This is in itself an estimation but can be done quite straightforward. For each clone class (code fragment and its copies), remove the size of the copies from the original system size. In addition you have to be aware of overlapping copied fragments. Any more detail here would require me to know more about the clone detection approach you use.

OwnerDisplayName: Nils Göde


答:
MVC is a presentation pattern. As such view and controller should only have responsibilities regarding presentation. Some permissions apply to the presentation, like an expert mode, experimental UI features or different designs. Those can be handled by the MVC-controller.

Many other kinds of permissions are relevant on several layers of the application. For example if you want to have users that can only view data and not change things:

the presentation layer has to hide the editing features

If an editing feature is called anyway this could/should be detected (by the application specific parts of the business layer, not the domain specific part of it - TrainEditor, not Train) and probably cause an exception

The data access layer can also check for writes too, but for more complex kinds of permissions that quickly requires too much knowledge of the business-layer to be a good idea.

There is some duplication in this approach. But as the presentation is usually volatile, one can make a good case for checking permission in the usually more stable part of application, even if that means some redundant checks in case the presentation layer works as intended.


答:
Here's how I see it:

Let's ignore the words "big data" for a while, as they are a pretty vague notion

You mentioned Hadoop. Hadoop does 2 things: allows you to have a sort of "virtual" drive which is distributed on multiple machines, with redundancy, that can be accessed via Hadoop's API as if it were a single, unitary, drive. It's called HDFS as in Hadoop Distributed File System. The other thing Hadoop does is allow you to execute Map-Reduce jobs (it's a framework for Map-Reduce). If we check out MapReduce's Wikipedia page, we see that:

MapReduce is a programming model for processing large data sets with a
  parallel, distributed algorithm on a cluster.

...

A MapReduce program
  is composed of a Map() procedure that performs filtering and sorting
  (such as sorting students by first name into queues, one queue for
  each name) and a Reduce() procedure that performs a summary operation
  (such as counting the number of students in each queue, yielding name
  frequencies)

...

'MapReduce' is a framework for processing parallelizable problems
  across huge datasets using a large number of computers

Also on this page, Hadoop is described as

Hadoop, Apache's free and open source implementation of MapReduce.

Now, Hadoop is written in Java, which is not a functional language. Also, if we look on Hadoop's page, we also find an example of how to create a MapReduce job in Java and deploy it in a Hadoop cluster.

Here's a Java example of a Fibonnaci MapReduce job for Hadoop.

I hope this answer your question, namely that BigData, and in particular a Fibonacci-creating MapReduce job doesn't "need" to be functional, aka you can implement it in OO languages if you want to (for example).

Of course that doesn't mean BigData "needs" to be OO-only either. You can very well use a functional language to implement a MapReduce like job. You can, for example, use Scala with Hadoop if you want to, via Scalding.

Other points I think are worth mentioning.

When doing recursion in Scala, if your code allows for it, Scala will do tail-call-optimization. However, since the JVM doesn't (yet) support tail-call-optimization, Scala achieves this by replacing, at compile time, your recursive calls with code equivalent to loops, as explained here. What this basically means is that doing recursive vs non-recursive code benchmarks using Scala is pointless, as they both end up doing the same thing at run time.

Title: Why Big Data Needs To Be Functional?


问:
How to store data for Windows Store apps?
I have a application which requires me to save data to a database not located on the users computer. Which approach is the best to save and access data for this scenario? Normally I would use Entity Framework and MS Sql Server but this seems not to a options for me with windows store apps. </p>

答:
You can store data directly to SQLite (local database) after obtaining SQLite WinRT wrapper. Limits on SQLite databases go as high as 140TB.

Store apps don't support ODBC, JDBC, ADO.Net and SQL Native client, etc. So we cannot access the remote database directly in store app. However, we can connect to the database via hosted service that itseld directly accesses database. Hosted service can be:

OData

REST

SOAP

Azure Mobile Services is another great option to store data in remote database.


问:
Factory Pattern and/or Dependency Injection?
I understand the concept and can use both the Factory Pattern and Dependency Injection, however they seem a little at odds with each other conceptually. Is it a case of using one over the other? Or can they be used in conjunction with each other?

If using DI would you hard code the creation of classes within a Factory? Wouldn't this defeat the point of DI? As the factory is dependant on the existence of the classes it creates, and thus would need them passed to the factory at runtime when using DI.

Or would you pass the classes that the factory is meant to create to the factory is meant to create? If so wouldn't that defeat the point of building a factory in the first place? As the Injector would basically be doing all the work of the factory.

Thank you very much for your attention, I look forward to your insights.

答:
If using DI would you hard code the creation of classes within a Factory? Wouldn't this defeat the point of DI?

No, it does not violate the Dependency Inversion (not Injection) Principle because it is the purpose of the factory is to create for us some concrete object.

Or would you pass the classes that the factory is meant to create to the factory is meant to create? If so wouldn't that defeat the point of building a factory in the first place? As the Injector would basically be doing all the work of the factory.

You are right!

Factory Patterns are the creation patterns - they are responsible for creating instances.

Dependency Injection patterns are about loose coupling and Dependency Inversion (Inversion of Control) - they inject instances that another instance need to do its job.

They address different problems and can be used in conjunction.
An example (maybe not some great but I hope that it would do the job):

```<code>class Player {
    string name;
}

interface PlayerFactory {
    Person create();
}

class RealPlayerFactory : PlayerFactory {
    return GetPlayerFromDatabase();
}

class RandomPlayerFactory : PlayerFactory {
    Person result = new Person();
    result.name = GenerateRandomName();
    return result;
}

class Team {
    Team(PlayerFactory playerFactory) {
        for (int i=0; i < 11; ++i) {
            AddPlayer( playerFactory.create() );
        }
    }
}
</code>```

Use Dependency Injection Patterns to introduce loose coupling.

Use Factory Patterns if you need to delegate the creation of objects.

Body:
If using DI would you hard code the creation of classes within a Factory? Wouldn't this defeat the point of DI?

No, it does not violate the Dependency Inversion (not Injection) Principle because it is the purpose of the factory is to create for us some concrete object.

Or would you pass the classes that the factory is meant to create to the factory is meant to create? If so wouldn't that defeat the point of building a factory in the first place? As the Injector would basically be doing all the work of the factory.

You are right!

Factory Patterns are the creation patterns - they are responsible for creating instances.

Dependency Injection patterns are about loose coupling and Dependency Inversion (Inversion of Control) - they inject instances that another instance need to do its job.

They address different problems and can be used in conjunction.
An example (maybe not some great but I hope that it would do the job):

class Player {
    string name;
}

interface PlayerFactory {
    Person create();
}

class RealPlayerFactory : PlayerFactory {
    return GetPlayerFromDatabase();
}

class RandomPlayerFactory : PlayerFactory {
    Person result = new Person();
    result.name = GenerateRandomName();
    return result;
}

class Team {
    Team(PlayerFactory playerFactory) {
        for (int i=0; i < 11; ++i) {
            AddPlayer( playerFactory.create() );
        }
    }
}

Use Dependency Injection Patterns to introduce loose coupling.

Use Factory Patterns if you need to delegate the creation of objects.


问:
When and how should I use exceptions?

The Setting

I often have trouble determining when and how to use exceptions. Let's consider a simple example: suppose I am scraping a webpage, say "http://www.abevigoda.com/", to determine if Abe Vigoda is still alive. To do this, all we need to do is download the page and look for times that the phrase "Abe Vigoda" appears. We return the first appearance, since that includes Abe's status. Conceptually, it will look like this:

```<code>def get_abe_status(url):
    # download the page
    page = download_page(url)

    # get all mentions of Abe Vigoda
    hits = page.find_all_mentions("Abe Vigoda")

    # parse the first hit for his status
    status = parse_abe_status(hits[0])

    # he's either alive or dead
    return status == "alive"
</code>```

Where parse_abe_status(s) takes a string of the form "Abe Vigoda is something" and returns the "something" part.

Before you argue that there are much better and more robust ways of scraping this page for Abe's status, remember that this is just a simple and contrived example used to highlight a common situation I'm in.

Now, where can this code encounter problems? Among other errors, some "expected" ones are:

download_page might not be able to download the page, and throws an IOError.

The URL might not point to the right page, or the page is downloaded incorrectly, and so there are no hits. hits is the empty list, then.

The web page has been altered, possibly making our assumptions about the page wrong. Maybe we expect 4 mentions of Abe Vigoda, but now we find 5.

For some reasons, hits[0] might not be a string of the form "Abe Vigoda is something", and so it cannot be correctly parsed.

The first case isn't really a problem for me: an IOError is thrown and can be handled by the caller of my function. So let's consider the other cases and how I might handle them. But first, let's assume that we implement parse_abe_status in the stupidest way possible:

```<code>def parse_abe_status(s):
    return s[13:]
</code>```

Namely, it doesn't do any error checking. Now, on to the options:

Option 1: Return None

I can tell the caller that something went wrong by returning None:

```<code>def get_abe_status(url):
    # download the page
    page = download_page(url)

    # get all mentions of Abe Vigoda
    hits = page.find_all_mentions("Abe Vigoda")

    if not hits:
        return None

    # parse the first hit for his status
    status = parse_abe_status(hits[0])

    # he's either alive or dead
    return status == "alive"
</code>```

If the caller receives None from my function, he should assume that there were no mentions of Abe Vigoda, and so something went wrong. But this is pretty vague, right? And it doesn't help the case where hits[0] isn't what we thought it was.

On the other hand, we can put in some exceptions:

Option 2: Using Exceptions

If hits is empty, an IndexError will be thrown when we attempt hits[0]. But the caller shouldn't be expected to handle an IndexError thrown by my function, since he has no idea where that IndexError came from; it could have been thrown by find_all_mentions, for all he knows. So we'll create a custom exception class to handle this:

```<code>class NotFoundError(Exception):
    """Throw this when something can't be found on a page."""

def get_abe_status(url):
    # download the page
    page = download_page(url)

    # get all mentions of Abe Vigoda
    hits = page.find_all_mentions("Abe Vigoda")

    try:
        hits[0]
    except IndexError:
        raise NotFoundError("No mentions found.")

    # parse the first hit for his status
    status = parse_abe_status(hits[0])

    # he's either alive or dead
    return status == "alive"
</code>```

Now what if the page has changed and there are an unexpected number of hits? This isn't catastrophic, as the code may still work, but a caller might want to be extra careful, or he might want to log a warning. So I'll throw a warning:

```<code>class NotFoundError(Exception):
    """Throw this when something can't be found on a page."""

def get_abe_status(url):
    # download the page
    page = download_page(url)

    # get all mentions of Abe Vigoda
    hits = page.find_all_mentions("Abe Vigoda")

    try:
        hits[0]
    except IndexError:
        raise NotFoundError("No mentions found.")

    # say we expect four hits...
    if len(hits) != 4:
        raise Warning("An unexpected number of hits.")
        logger.warning("An unexpected number of hits.")

    # parse the first hit for his status
    status = parse_abe_status(hits[0])

    # he's either alive or dead
    return status == "alive"
</code>```

Lastly, we might find that status isn't either alive or dead. Maybe, for some odd reason, today it turned out to be comatose. Then I don't want to return False, as that implies that Abe is dead. What should I do here? Throw an exception, probably. But what kind? Should I create a custom exception class?

```<code>class NotFoundError(Exception):
    """Throw this when something can't be found on a page."""

def get_abe_status(url):
    # download the page
    page = download_page(url)

    # get all mentions of Abe Vigoda
    hits = page.find_all_mentions("Abe Vigoda")

    try:
        hits[0]
    except IndexError:
        raise NotFoundError("No mentions found.")

    # say we expect four hits...
    if len(hits) != 4:
        raise Warning("An unexpected number of hits.")
        logger.warning("An unexpected number of hits.")

    # parse the first hit for his status
    status = parse_abe_status(hits[0])

    if status not in ['alive', 'dead']:
        raise SomeTypeOfError("Status is an unexpected value.")

    # he's either alive or dead
    return status == "alive"
</code>```

Option 3: Somewhere in between

I think that the second method, with exceptions, is preferable, but I'm not sure if I'm using exceptions correctly within it. I'm curious to see how more experienced programmers would handle this.

答:
If I was writing a function

```<code> def abe_is_alive():
</code>```

I would write it to return True or False in the cases where I am absolutely certain of one or the other, and raise an error in any other case (e.g. raise ValueError("Status neither 'dead' nor 'alive'")). This is because the function calling mine is expecting a boolean, and if I can't provide that with certainty the regular program flow shouldn't continue.

Something like your example of getting a different number of "hits" than expected, I would probably ignore; as long as one of the hits still matches my pattern "Abe Vigoda is {dead|alive}", that's fine. This allows the page to be rearranged but still gets the appropriate information.

Rather than

```<code>try:
    hits[0]
except IndexError:
    raise NotFoundError
</code>```

I would check explicitly:

```<code>if not hits:
    raise NotFoundError
</code>```

as this tends to be "cheaper" then setting up the try.

I agree with you on IOError; I also wouldn't try to error handle connecting to the website - if we can't, for some reason, this isn't the appropriate place to handle it (as it doesn't help us answer our question) and it should pass out to the calling function.

Title: When and how should I use exceptions?

Body:
If I was writing a function

 def abe_is_alive():

I would write it to return True or False in the cases where I am absolutely certain of one or the other, and raise an error in any other case (e.g. raise ValueError("Status neither 'dead' nor 'alive'")). This is because the function calling mine is expecting a boolean, and if I can't provide that with certainty the regular program flow shouldn't continue.

Something like your example of getting a different number of "hits" than expected, I would probably ignore; as long as one of the hits still matches my pattern "Abe Vigoda is {dead|alive}", that's fine. This allows the page to be rearranged but still gets the appropriate information.

Rather than

try:
    hits[0]
except IndexError:
    raise NotFoundError

I would check explicitly:

if not hits:
    raise NotFoundError

as this tends to be "cheaper" then setting up the try.

I agree with you on IOError; I also wouldn't try to error handle connecting to the website - if we can't, for some reason, this isn't the appropriate place to handle it (as it doesn't help us answer our question) and it should pass out to the calling function.


答:
The recommendation in Python is to use exceptions to indicate failure. This is true even if you expect failure on a regular basis.

Look at it from the perspective of the caller of your code:

```<code>my_status = get_abe_status(my_url)
</code>```

What if we return None? If the caller doesn't specifically handle the case that get_abe_status failed, it will simply try to continue on with my_stats being None. That may produce a difficult to diagnose bug later on. Even if you do check for None, this code has no clue why get_abe_status() failed.

But what if we raise an exception? If the caller doesn't specifically handle the case, the exception will propagate upward eventually hitting the default exception handler. That may not be the what you want, but its better then introducing a subtle bug elsewhere in the program. Additionally, the exception gives information about what went wrong which is lost in the first version.

From the caller's perspective, its simply more convenient to get an exception than a return value. And that's the python style, to use exceptions to indicate failure conditions not return values.

Some will take a different perspective and argue that you should only use exceptions for cases you never really expect to happen. They argue that normally running running could should not raise any exceptions. One reason that is given for this is that exceptions are grossly inefficient, but that's not actually true for Python.

A couple of points on your code:

```<code>try:
    hits[0]
except IndexError:
    raise NotFoundError("No mentions found.")
</code>```

That's a really confusing way to check for an empty list. Don't induce an exception just to check something. Use an if.

```<code># say we expect four hits...
if len(hits) != 4:
    raise Warning("An unexpected number of hits.")
    logger.warning("An unexpected number of hits.")
</code>```

You do realize that the logger.warning line will never run right?

Title: When and how should I use exceptions?

Body:
The Setting

I often have trouble determining when and how to use exceptions. Let's consider a simple example: suppose I am scraping a webpage, say "http://www.abevigoda.com/", to determine if Abe Vigoda is still alive. To do this, all we need to do is download the page and look for times that the phrase "Abe Vigoda" appears. We return the first appearance, since that includes Abe's status. Conceptually, it will look like this:

```<code>def get_abe_status(url):
    # download the page
    page = download_page(url)

    # get all mentions of Abe Vigoda
    hits = page.find_all_mentions("Abe Vigoda")

    # parse the first hit for his status
    status = parse_abe_status(hits[0])

    # he's either alive or dead
    return status == "alive"
</code>```

Where parse_abe_status(s) takes a string of the form "Abe Vigoda is something" and returns the "something" part.

Before you argue that there are much better and more robust ways of scraping this page for Abe's status, remember that this is just a simple and contrived example used to highlight a common situation I'm in.

Now, where can this code encounter problems? Among other errors, some "expected" ones are:

download_page might not be able to download the page, and throws an IOError.

The URL might not point to the right page, or the page is downloaded incorrectly, and so there are no hits. hits is the empty list, then.

The web page has been altered, possibly making our assumptions about the page wrong. Maybe we expect 4 mentions of Abe Vigoda, but now we find 5.

For some reasons, hits[0] might not be a string of the form "Abe Vigoda is something", and so it cannot be correctly parsed.

The first case isn't really a problem for me: an IOError is thrown and can be handled by the caller of my function. So let's consider the other cases and how I might handle them. But first, let's assume that we implement parse_abe_status in the stupidest way possible:

```<code>def parse_abe_status(s):
    return s[13:]
</code>```

Namely, it doesn't do any error checking. Now, on to the options:

Option 1: Return None

I can tell the caller that something went wrong by returning None:

```<code>def get_abe_status(url):
    # download the page
    page = download_page(url)

    # get all mentions of Abe Vigoda
    hits = page.find_all_mentions("Abe Vigoda")

    if not hits:
        return None

    # parse the first hit for his status
    status = parse_abe_status(hits[0])

    # he's either alive or dead
    return status == "alive"
</code>```

If the caller receives None from my function, he should assume that there were no mentions of Abe Vigoda, and so something went wrong. But this is pretty vague, right? And it doesn't help the case where hits[0] isn't what we thought it was.

On the other hand, we can put in some exceptions:

Option 2: Using Exceptions

If hits is empty, an IndexError will be thrown when we attempt hits[0]. But the caller shouldn't be expected to handle an IndexError thrown by my function, since he has no idea where that IndexError came from; it could have been thrown by find_all_mentions, for all he knows. So we'll create a custom exception class to handle this:

```<code>class NotFoundError(Exception):
    """Throw this when something can't be found on a page."""

def get_abe_status(url):
    # download the page
    page = download_page(url)

    # get all mentions of Abe Vigoda
    hits = page.find_all_mentions("Abe Vigoda")

    try:
        hits[0]
    except IndexError:
        raise NotFoundError("No mentions found.")

    # parse the first hit for his status
    status = parse_abe_status(hits[0])

    # he's either alive or dead
    return status == "alive"
</code>```

Now what if the page has changed and there are an unexpected number of hits? This isn't catastrophic, as the code may still work, but a caller might want to be extra careful, or he might want to log a warning. So I'll throw a warning:

```<code>class NotFoundError(Exception):
    """Throw this when something can't be found on a page."""

def get_abe_status(url):
    # download the page
    page = download_page(url)

    # get all mentions of Abe Vigoda
    hits = page.find_all_mentions("Abe Vigoda")

    try:
        hits[0]
    except IndexError:
        raise NotFoundError("No mentions found.")

    # say we expect four hits...
    if len(hits) != 4:
        raise Warning("An unexpected number of hits.")
        logger.warning("An unexpected number of hits.")

    # parse the first hit for his status
    status = parse_abe_status(hits[0])

    # he's either alive or dead
    return status == "alive"
</code>```

Lastly, we might find that status isn't either alive or dead. Maybe, for some odd reason, today it turned out to be comatose. Then I don't want to return False, as that implies that Abe is dead. What should I do here? Throw an exception, probably. But what kind? Should I create a custom exception class?

```<code>class NotFoundError(Exception):
    """Throw this when something can't be found on a page."""

def get_abe_status(url):
    # download the page
    page = download_page(url)

    # get all mentions of Abe Vigoda
    hits = page.find_all_mentions("Abe Vigoda")

    try:
        hits[0]
    except IndexError:
        raise NotFoundError("No mentions found.")

    # say we expect four hits...
    if len(hits) != 4:
        raise Warning("An unexpected number of hits.")
        logger.warning("An unexpected number of hits.")

    # parse the first hit for his status
    status = parse_abe_status(hits[0])

    if status not in ['alive', 'dead']:
        raise SomeTypeOfError("Status is an unexpected value.")

    # he's either alive or dead
    return status == "alive"
</code>```

Option 3: Somewhere in between

I think that the second method, with exceptions, is preferable, but I'm not sure if I'm using exceptions correctly within it. I'm curious to see how more experienced programmers would handle this.

Body:
The recommendation in Python is to use exceptions to indicate failure. This is true even if you expect failure on a regular basis.

Look at it from the perspective of the caller of your code:

my_status = get_abe_status(my_url)

What if we return None? If the caller doesn't specifically handle the case that get_abe_status failed, it will simply try to continue on with my_stats being None. That may produce a difficult to diagnose bug later on. Even if you do check for None, this code has no clue why get_abe_status() failed.

But what if we raise an exception? If the caller doesn't specifically handle the case, the exception will propagate upward eventually hitting the default exception handler. That may not be the what you want, but its better then introducing a subtle bug elsewhere in the program. Additionally, the exception gives information about what went wrong which is lost in the first version.

From the caller's perspective, its simply more convenient to get an exception than a return value. And that's the python style, to use exceptions to indicate failure conditions not return values.

Some will take a different perspective and argue that you should only use exceptions for cases you never really expect to happen. They argue that normally running running could should not raise any exceptions. One reason that is given for this is that exceptions are grossly inefficient, but that's not actually true for Python.

A couple of points on your code:

try:
    hits[0]
except IndexError:
    raise NotFoundError("No mentions found.")

That's a really confusing way to check for an empty list. Don't induce an exception just to check something. Use an if.

# say we expect four hits...
if len(hits) != 4:
    raise Warning("An unexpected number of hits.")
    logger.warning("An unexpected number of hits.")

You do realize that the logger.warning line will never run right?


答:
When you make heavy use of dependency injection, you separate your code into parts with classes/objects holding features & functions, and code where the creating of the former takes place and the dependencies are resolved. The latter can be either done by

a DI container

Factory classes

So DI is not contrary to the use of Factories, in fact, when you do DI without a DI container you will typically need a lot of factories.

See this blog post for a more complete explanation.

Title: Factory Pattern and/or Dependency Injection?

Body:
I understand the concept and can use both the Factory Pattern and Dependency Injection, however they seem a little at odds with each other conceptually. Is it a case of using one over the other? Or can they be used in conjunction with each other?

If using DI would you hard code the creation of classes within a Factory? Wouldn't this defeat the point of DI? As the factory is dependant on the existence of the classes it creates, and thus would need them passed to the factory at runtime when using DI.

Or would you pass the classes that the factory is meant to create to the factory is meant to create? If so wouldn't that defeat the point of building a factory in the first place? As the Injector would basically be doing all the work of the factory.

Thank you very much for your attention, I look forward to your insights.


答: Is Python pass by reference or pass by value is also a very good question.</p>

Title: Python interview questions

Body:
I am going to interview within two weeks for an internship that would involve Python programming.

Can anyone suggest what possible areas should I polish? I am looking for commonly asked stuff in interviews for Python openings. Apart from the fact that I have already been doing the language for over a year now, I fail to perceive what they can ask me.

Like for a C or C++ interview, there are lots of questions ranging from reversing of strings to building linked lists, but for a Python interview, I am clueless.

Personal experiences and/ or suggestions are welcomed.


问:
Separate the renderer from the business model
I have a small responsibility separation issue that I hope someone can clarify. I have a small model composed by 2 classes: GameBoard and GamePiece, and the obvious relationship is that a GameBoard can have several GamePieces.

In the application I'm implementing, GameBoard and GamePiece contain data related to rendering in the screen (Update/Draw methods, Textures, etc) as well as their logic (gameboard number of squares, pieceType, etc). Updating/Drawing the GameBoard causes to update/draw the pieces as well. However, in order to keep the single responsibility principle, I decided to separate the logic from the rendering. But I have some troubles to implement it adequately.

I came up to a couple of solutions and I'm not sure which one is the best:

1- Create GameBoardRenderer and GamePieceRenderer classes (who would store Textures, updating and drawing), and every instance these Renderer classes would be related to one GameBoard or GamePiece respectively. The problem I see is that it forces me to keep a dual relationship between GameBoard and GamePiece, and GameBoardRenderer and GamePieceRenderer, and ensure that it is always consistent.

2- Create GameBoardRenderer and GamePieceRenderer, but make them inherit from GameBoard and GamePiece respectively, bringing all the rendering stuff to those classes, while keeping the association at the GameBoard and GamePiece classes. The problem is that when I call the Update/Draw method of GameBoard, I won't be able to call the GamePieceRenderer Update and Draw method (as no relationship will be available).

What should I do? Is there any better solution?

Thank you very much.

答:
I had almost the exact same problem when I started using XNA.  I'm still playing around with patterns to solve it, though :)

The latest thing I tried involves borrowing from MVVM.  In XNA/Monogame land, you can inherit from a GameComponent class and register that component with the update/rendering engine (I may be getting the terms wrong here, but the general idea is correct).

Here's how I've broken things down:

GameComponents registered with the update/rendering engine are analogous to my MVVM Views

GameComponents not registered with the update/rendering engire, but managed by registered GameComponents are analogous to my MVVM ViewModels

Actual Model classes are injected into my GameComponents to controls the state of my GamePiece/GameBoard/etc.  These model classes are completely unaware of the update or rendering mechanics.  I would write my unit tests against these.

This kind of setup means I only register a handful of GameComponents with the engine (the views).  Those GameComponents are then -in a sense- bound to other GameComponents (the viewModels) which are responsible for triggering updates in the system state and managing any rendering control logic.  And finally, these viewModel analogous GameComponents each contain a Model which is responsible for the state and logic of what is eventually drawn on screen.  The key here is that the Model is completely decoupled from the update/rendering engine.

I've only just started applying this approach.  I'm sure I'll find problems with it... but so far it has helped me refactor an old monolithic XNA game I wrote 5 or so years ago.


答:
I think that:

it's the game loop's responsibility to know which objects are drawable/renderable. You should make a base class/interface which holds some kind of "render" or "draw" method, possibly accepting any necessary arguments that the game loop will pass when calling it (like the GL context object for OpenGL rendering, etc).

each of your render-capable objects should contain their own drawing code, as an implementation of the "render" method of the base interface/class which they should extend. You can further refine this by extracting common rendering code to the base class (if you chose that over a base interface) or to the game loop itself, i.e. for a sprite-based 2D game, the game loop could contain all the actual sprite objects, and the render-able objects only inform the game loop which sprite is theirs, and where it should be placed, and it's the game loop itself that runs the sprite-drawing code.

Title: Separate the renderer from the business model

Body:
I have a small responsibility separation issue that I hope someone can clarify. I have a small model composed by 2 classes: GameBoard and GamePiece, and the obvious relationship is that a GameBoard can have several GamePieces.

In the application I'm implementing, GameBoard and GamePiece contain data related to rendering in the screen (Update/Draw methods, Textures, etc) as well as their logic (gameboard number of squares, pieceType, etc). Updating/Drawing the GameBoard causes to update/draw the pieces as well. However, in order to keep the single responsibility principle, I decided to separate the logic from the rendering. But I have some troubles to implement it adequately.

I came up to a couple of solutions and I'm not sure which one is the best:

1- Create GameBoardRenderer and GamePieceRenderer classes (who would store Textures, updating and drawing), and every instance these Renderer classes would be related to one GameBoard or GamePiece respectively. The problem I see is that it forces me to keep a dual relationship between GameBoard and GamePiece, and GameBoardRenderer and GamePieceRenderer, and ensure that it is always consistent.

2- Create GameBoardRenderer and GamePieceRenderer, but make them inherit from GameBoard and GamePiece respectively, bringing all the rendering stuff to those classes, while keeping the association at the GameBoard and GamePiece classes. The problem is that when I call the Update/Draw method of GameBoard, I won't be able to call the GamePieceRenderer Update and Draw method (as no relationship will be available).

What should I do? Is there any better solution?

Thank you very much.


问:
Base class should have no knowledge of its subtypes?
What's the OO principle that states (in sum):

A base object should have no knowledge of its subtypes.

I thought it was Liskov Substitution but after reading that wikipedia article I don't believe I'm correct. Thanks in advance!

答:
This probably comes under dependency inversion.

The parent is a higher level abstraction than its child so it cannot be dependant on the child's implementation. It cannot know that a lower level abstraction exists or else it would by definition be dependant on it..


问:
How should I draw the (special) is predicate, which is used for arithmetic, in a Prolog search tree?
I normally construct my search tree by following the common convention:

Place Queries or Goals in need of unification inside node boxes.

Write down decision points on the edges, where Prolog has assigned an element to a variable.

Leaf nodes which are fully satisifed will be an empty box, they represent a solution.

Leaf nodes which can not be satisifed and represent failed attempts will have the unfulfilled goal in their box, to make them even more clear I also follow the convention of marking them by placeing a cross symbol below them.

The above way has the nice side effect that it's easy to see the decision points. But what about creating a search tree for something like:

```<code>accLen([_|T],A,L)  :-    Anew  is  A+1,  accLen(T,Anew,L).
accLen([],A,A).
</code>```

How should the assignment of Anew be represented in the search tree? It's not a decision point, the code has no other option then assigning it 1 plus the current value of A. Do you still place it on the edge, but underline it or something?

答:
In my view, an is predicate is not much different from an explicit unification via = or an implicit one via matching of a clause to the input: it causes a variable to be bound. It doesn't leave the interpreter any less choice than X = 3 does, it's just a bit cleverer about how to retrieve the one possible value that must be assigned.

The only thing that is different is that the is cannot succeed until the right hand side is instantiated. If you want to represent this limitation, then you need some special representation, but otherwise I would treat = and is the same.


答:
By the sound of it, this looks like a case where the Visitor patterns comes in handy.

Within this pattern, the GameBoard and GamePiece classes contain all the game-related logic, but no rendering logic. Instead, the rendering logic for both the GameBoard and GamePiece classes is located in a GameRenerer class.

When the board needs to be rendered, a GameRenderer instance is created and passed to the GameBoard::Draw method. The GameBoard class then tells the GameRenderer class to draw a board (passing itself to provide all the relevant information) and calls the Draw method of all the GamePieces on the board, again passing the GameRenderer instance.


答:
It is the Open Closed Principle.

Classes should be open to extension, but closed to modification.

If a class knows about its subtypes, that implies you can't just add one (extend the class) without modifying the base type (which should be prohibited).

Title: Base class should have no knowledge of its subtypes?

Body:
What's the OO principle that states (in sum):

A base object should have no knowledge of its subtypes.

I thought it was Liskov Substitution but after reading that wikipedia article I don't believe I'm correct. Thanks in advance!


答: I would go along the list in this answer. Try to refresh what you know following that list as far as you can. Don't worry if you cannot make it until the very end.</p>

Title: Python interview questions


问:
Sell product containing purchased GPL software
I recently purchased a product (a website template, licensed by GNU GPL 2.0). My product, which is a web software, coded in PHP, uses that web template as its appearance.

The question is: How can I sell a software which includes some parts of a GNU GPL 2.0 commercial website template? Do I have to pay a license for the website template each time I sell mine?

Thanks.

答:
Purchasing GPL'ed software is fine. The fact that the software is GPL'ed means that you are free to redistribute the GPL'ed software without any restrictions. You can, for example, make it freely available on your website. Or you can sell it to someone else; you just can't prevent them from selling it, and you can't sell just the binary code (although that may not be an issue in your case.)

You are welcome to sell software that contains GPL'ed software, but the software that you sell is GPL'ed as well. Typically, organizations will sell the software with customization, consulting, or support services. You can't legally prevent the people who purchase it from you from reselling it (or giving it away), but there is typically no incentive for them to do so because what they have is customized for their own application.

This is the business model that Red Hat uses.


问:
Why does Mono for Android cost money if the mono project is opensource and therefore everything based on it must be opensource?
Why does Mono for Android cost money if the mono project is opensource and therefore everything based on it must be opensource?</p>

答:
There are two "free" aspects to open-source software:

Free as in speech,

Free as in beer.

Free as in beer means you don't have to pay for it.  Free as in speech means that you have the freedom to examine the source code, make derived works, etc.

Mono is based on four open source licenses, as described here:

The C# compiler is dual-licensed under the MIT/X11 license and the GNU General Public License (GPL).

The tools are released under the terms of the GNU General Public License (GPL).

The runtime libraries are under the GNU Library GPL 2.0 (LGPL 2.0).

The class libraries are released under the terms of the MIT X11 license.

ASP.NET MVC, the Managed Extensibility Framework (MEF), the Dynamic Language Runtime (DLR), System.Data.Services.Client, parts of System.Numerics and ASP.NET AJAX client software are released by Microsoft under the open source Microsoft Permissive License, some of them are dual licensed also as Apache2.

The most important aspect of these licenses is the "copyleft" provision in the GPL.  The copyleft provision essentially prevents you from using those libraries and code in a proprietary application, and then distributing it to users or customers.  Distribution is what triggers the copyleft provision.  Licenses such as MIT and Apache that do not have the copyleft provision in them do not prevent you from using the code in closed-source, commercial applications.

Because the class libraries are licensed under MIT, you are not required to obtain a commercial license to write and distribute your own commercial applications, if you can otherwise abide by the terms of the Lesser/Library GPL, which only requires that you provide any source code changes that you make to the GPL libraries in Mono back to the community.

Contributors who contribute code to the Mono project must assign copyright of their code to the Mono project, so that Xamarin can redistribute the code under a different license.  This is how they are able to make certain components of Xamarin proprietary, so that they can charge for it.  Because Xamarin is the copyright holder for the entire Mono project, they can redistribute their code in any way they see fit.


问:
Splitting object definitions (catalog) from instances (physical objects)
I am wondering if there is a design pattern for such problem:

Let's say we are building a web shop for a doors and windows manufacturer, where customer has a catalog (list) of products, from which he can choose some and customize them, before placing an order.

Each product has it's properties defined, like name, price, description. Obviously, the customer is not allowed to change any of these properties. But there is a space to customize the product. When he chooses a window, then he can choose it's colour, dimensions, perhaps a color of glass and choose some additional features. When he chooses doors, then he can choose a color, dimension, but also a type of the lock.

First idea that came to my mind is:

Create products definitions classes (WindowDefintion, DoorsDefinition), which hold information about the name, price, description. These are listed in a catalog

Create product instances classes (Window, Doors), which hold reference to the product, but also add customizable fields, which are specific to certain instance.

Disadvantages are perhaps silly, because it is mostly about creating a definition class for each instance class, but this involves more doubled amount of database tables and repositiories as well. I was just wondering if there is some other solution?

This example is not the case. I am using it to ease understanding of the problem. In the case, products don't have a good common generalization, which a Product would give in this case (good for having name, description and price properties).

答:
Your abstractions appear too fine grained and you are thinking about modelling your persistence layer in the same way as your domain.

There is trade off to be made here.

On the one hand if you model your products like this in a database, you will indeed end up with a larger number of tables, each change to a product will require schema, repository, domain and consumer/application changes. This is IMO quite a brittle design.

If you make your schema less aware of product implementations, instead opting to store custom values in a more key/value fashion for each product customisation, each change to a product will  likely not require schema and repository changes, only domain and application changes. It will complicate things like searching/retrieval and rehydration of domain objects but this is typically what a service layer and domain model is for, abstracting away the specifics of persistence.

It depends on your application requirements which aren't really clear but I'd always lean towards option number two.

I would focus on modelling an abstract Product type containing the common elements (ids, names, descriptions, prices) and use something like a decorator or builder pattern to add the product specific things into a collection which is accessed using subtype properties created by the patterns.

Persistence/Repository layers would only require knowledge to Save/Load the collection
into the proper types which could be done using a Factory.

As requirements change and complexity increases for product options and customizations, it becomes far easier to manage this kind of model where your logic is in the domain layer and not reflected in your persistence layer.


问:
Class structure to implement a Stack Exchange-like review system
I was reviewing some threads on Stack Overflow and started asking myself how I would design my classes and relationships to create such a system.

My Goal -

I want to build a review system like the Stack Exchange review system.

Let's take a look at how the review system works on Stack Exchange. I will only refer to the Suggested Edits functionality to keep it simple.

Un-experienced user (less than 2000 rep) edits someone post

Add an entry to the "review" system tagged 'suggested-edit'

Experienced user (more than 2000 rep) can review "suggested edits" one by one

As an experienced user I can:

See the diff between the original content and the edited content

Approve the edit

Reject the edit

Improve the edit

Skip to the next review

Final note about other review types. We could imagine "tagging" the reviews with the corresponding types since the actions are the same.

Design

I would start with a Review model. We could have one sub-class for each review type, allowing custom attributes and methods for each type in the future.

ruby

```<code>class Review
class Review::SuggestedEdit < Review
class Review::FirstPost     < Review
class Review::LateAnswer    < Review
class Review::LowQuality    < Review
</code>```

A Review object would have 2 references:

Original Content

Edited Content

Approve

Replace original content by edited content.

Mark the review as approved.

Move to the next review.

Reject

Log the reason for rejection.

Mark the review as rejected.

Move to the next review.

Improve

Directly edit edited content.

Approve.

(We could imaging creating a new Review for this improvement.)

Move to the next review.

Skip

Move to the next review.

How should I structure my classes in order to build such a review system?

答:
I'm not sure how I would model this exactly, but what you are describing is very much like a version control system. Like Svn for a VCS or git for a Distributed VCS

The ability to track changes, view/visualise or edit diffs, log, merge, revert, tag/label is all there and is particularly good with text diffs.