问:
SQLDatabase: Read a lot of data at once and process in memory or read the data when I need it?
I'm not sure how to approach this problem.
I require a big chunk of data records from the SQL server. This chunk is based on variables, so I don't know before what records I need.
I need to do a large series of calculations and each calculation requires one (or more) records from this chunk of data. Again: I do not know which records are required.

Should I:

A. Load this data into the application memory all at once

This creates a single connection to the DB, loads ALL required data by a query command (and a forward only DataReader) and then doesn't bother the SQL server anymore.

The datafetch seems to be slow, since it's reading hundred of thousands of lines into memory

B. Whenever the calculation needs data, retrieve it from the database

This would open and close a connection to the SQL db multiple times per second.

The initial datafetch is reduced to only a few miliseconds, but creates a massive load on the SQL server during calculation.

答:
Firstly, if you can turn your whole calculation in to an SQL query (or a series of queries or a stored procedure) then do so. Databases are good at this stuff, and you or a DBA may be able to do a lot to improve the query if it's still too slow.

If not:

Use a connection pool. Not doing so is usually crazy, unless you're writing a script that only connects once or twice.

If you're testing this in a development environment with a local DB, beware that there can be a big difference in performance characteristics compared to a production one and don't over-optimize based on what you measure. Network delays in particular could catch you out. Fetching one row at a time may be fine with a low network latency, and awful with a high one.

Database sizes are usually bigger in production, and go up over time. If you fetch all the data in advance you could get caught out and run out of memory (unless you know more about your data then we do...).

As Pieter B suggests, you're probably better fetching data in batches if you really need a large number of rows. Then you'll neither blow everything else out of your server's memory, nor have a network latency and query overhead on every row. It'll also help if you want to report progress to the user.

If you're really serious about making it go as fast as possible and not using SQL to do it, then you could try parallelizing your code. Then you can be calculating with one set of data whilst fetching the next, and if your production DB has multiple cores and disks you can parallelize in the DB, too. You could also look at caching, if that's appropriate (memcached and similar, or directly in your server if you know your data sizes well enough).


问:
Hexagonal architecure - handle multiple returns from domain logic
I'm looking at using hexagonal/ports & adapters design in some code I'm working on and for the most part I'm happy but there is one part that I'm struggling with which how to handle the need for different return values from a single call.

I'll use an example to better illustrate, this is pseudo code so names aren't represntative of real code.

If I have a domain "service" which has a method AddEntity I can have 3 returns:

Newly added object

Invalid Data

Entity already exists

The adapter that uses this "service" will then take the return and will send the data in the object back (it may transform it to a "view model" first).

In C# the adapter maybe a WebApi controller with code something like this:

```<code>public IHttpActionResult Post(DataViewModel entityData)
{
    var item = this.service.AddEntity(entityData.Name, entityData.Description);

    if (item == null)
    {
        return this.StatusCode(HttpStatusCode.Conflict);
    }

    var viewModel = Mapper.Map<EntityDTO, DataViewModel>(item);
    return this.Created(this.Url.Link("DefaultApi", new { controller = "Entity", id = viewModel.Id }), viewModel);
}
</code>```

The problem as you can see is at the moment it can only deal with 2 returns, either it gets the entityDTO which it maps and returns to the client or it gets null and just returns a Conflict HttpStatus code.

What I'm trying to work out is how I could get back to the adapter, controller in example above, is either the object or one of the two messages.

The approaches I've considered are:

extending the entityDTO class to have additional information which would allow me to pass something indicating a problem (an enum maybe?)

raising typed exceptions and handling the exceptions

raising events

if I used the enum then the controller code would look something like this:

```<code>public IHttpActionResult Post(DataViewModel entityData)
{
    var item = this.service.AddEntity(entityData.Name, entityData.Description);

    if(item.result == Result.Conflict)
    {
        return this.StatusCode(HttpStatusCode.Conflict);
    }

    if (item.result == Result.Invalid)
    {
        return this.StatusCode(HttpStatusCode.Invalid);
    }

    var viewModel = Mapper.Map<EntityDTO, DataViewModel>(item);
    return this.Created(this.Url.Link("DefaultApi", new { controller = "Entity", id = viewModel.Id }), viewModel);
}
</code>```

Of these extending the DTO seems the least bad option but I'm unsure if I've just missed something in the pattern which gives an easy way to do this.

Is there any specific way to do this I've missed? or is one of the options for sorting this I mentioned above a better way than the others?

答:
Communicating errors is not part of the responsibility of a DTO, so adding a field to the DTO for that purpose should really be a last-resort option.

The typical solutions for the problem where you return either an object or one out of a set of errors are:

Returning a Variant record that holds either the object or the error code,

Returning a tuple of object and error code,

Returning an error code (with a special value for "no error"), and using an out-parameter for the object,

Returning the object and using an out-parameter for the error code,

Returning the object and using an exception to communicate the error.

Which option you choose depends in part on the possibilities and culture around the language you use. The option with the Variant record probably communicates the most clearly that you get either an object or an error.

ContentLicense: CC BY-SA 3.0


问:
Is it wrong to make any form of business decision in a Controller?
I'm building a prototype web application using ASP.NET MVC 5. Part of the application is the display of a grid of records, each of which has a button action to 'Archive' that record. Another page displays the archived records. A WCF service provides the Model and persistence.

I have built a controller for each of the pages and in each controller I retrieve all of the records and then select either the current or archived records and display only those. There is an additional method on the current records Controller to set the Archive status of the record and then redisplay the current records.

I suspect that this is a potentially poor design as business decisions are being made in the Controllers and not the Model. Should I instead create a Model 'layer' in the MVC application with methods that return either current or archived records as required, or update the status of records, thus 'wrapping' the WCF Service, or is this adding a layer of complexity where it is not necessary?

What is the pure decision to be made based on the MVC concept? Should any business decision (even one as simple as filtering records based on status) be made in the Model and not the Controller?

答:
I don't use ASP.Net, but when it comes to MVC, I like to keep all layers clearly separated.

It is better to separate the domain model from the persistence layer, so that you can easily provide another one if needed. The domain model should contain in my view only basic properties and methods. Methods that involves processing, even the simplest ones, should be implemented in business objects. The controller is somehow related to the MVC framework, and, on the other hand, you want your service layer to be independent of it.

That being said, in your case, the filtering, if it doesn't involve any additional processing, could also sit in the persistence layer.

The method setArchiveStatus could sit in the model, if, again, doesn't involve further processing and it is only a domain model property.


问:
Adding quirks from an old system to a new system because that's what people are used to - a term for this?
Is there a term for the above?  When building a new system developers are sometimes  instructed (that is a different issue) to "keep things as they are", regardless of how inefficient or unusable they are, albeit in the name of usability, training or something along those lines.

Is there a term for this?  And if there is, is there any decent literature on addressing this type of problem?

答:
Legacy code or legacy feature may also convey your meaning,
particularly when the quirks to be preserved used to be intentional,
or have become so.  These term refer to the code or features intended
to achieve the desired result.
This is referenced in wikipedia:

Legacy code is source code that relates to a no-longer supported or manufactured operating system or other computer technology. The
  term can also mean code inserted into modern software for the purpose
  of maintaining an older or previously supported feature — for example
  supporting a serial interface even though many modern systems do not
  have a serial port. It may also be in the form of supporting older
  file formats that may have been encoding in non-ASCII characters, such
  as EBCDIC

Backward compatibility, or downward compatibility, is the property of
containing enough legacy code to be operationally compatible with
older versions of the system. It is also referenced in Wikipedia:

In telecommunications and computing, a product or technology is
  backward compatible or downward compatible if it can work with input
  generated by an older product or technology such as a legacy
  system. If products designed for the new standard can receive,
  read, view or play older standards or formats, then the product is
  said to be backward-compatible; examples of such a standard include
  data formats and communication protocols. Modifications to a system
  that do not allow backward compatibility are sometimes called
  "breaking changes.

Quirk parity is apparently a recent expression, hardly used on the
web (only 40 occurences of "quirk parity" quoted, including repeats, on Google, though it is 1,190,000 when the 2 words are separate, not quoted). It does not refer to
the addition of such legacy code or quirks, but to a state of the system when it
contains enough legacy code to fully mimic a former version of itself. It may be seen as an ultimate form of backward
compatibility. It may also be seen as a technical standstill if the parity
covers both the can and the can't, the do and the don't, though this still leave room for performance improvement (unless bad performance is considered too as an important quirk).


问:
Using ng-init to initialize data in Angular controller
Recently I came across the following in one of our projects. In one of our MVC views they are passing model data to an Angular controller through ngInit directive.

In xxx.cshtml:

```<code><div ng-controller="AssessmentController"
     ng-init="Init('@Model.Status','@Model.ARN','@Model.AssessmentID','@Model.AssessorID',@Model.Contents, @Model.Date_of_Assessment.ToJsonTicks(),'@Model.HouseReferenceID',@Newtonsoft.Json.JsonConvert.SerializeObject(Model.House))">
</code>```

I pointed out that according to Angular documentation, ngInit directive is not to be used to to initialize controllers.

Instead what I suggested was to send the ID in ngInit directive:

```<code><div ng-controller="AssessmentController"
     ng-init="Init('@Model.AssessmentID'">
</code>```

Then after that use $http service to get the remainder of data from the Angular controller.

The developer is refusing my idea saying it's faster to just send all the data through ngInit directive instead of having to do another call to get the data inti the Angular controller.

What do you think about this scenario? The only point I have right now is that this code is ugly and it not according to standards. How would you convince a developer to follow the path I suggested? Or am I completely wrong here?

答:
Short version: Why are you serving up Angular views dynamically?

The root of the problem

Looking at your example, it seems like you're using Razor views to inject the model's data into the view.  This seems to be a fairly counterproductive way of getting data into Angular.  The full route is something like:

MVC controller -> Razor View -> Angular controller -> Angular View

Through that, you're embedding your model through a variety of layers, converting it back and forth.

To understand why this is problematic, let's take a step back. Angular is typically employed as a single page application (SPA) framework, where you serve up the HTML template itself once-off (vanilla HTML with ng-* directives).  At some later point, Angular can then use this template in conjunction with a model (a JavaScript object), to render the view, and keep it data bound to the model.  These models are typically retrieved directly as JSON objects from the server.

So, I'd say that typical usage would involve very little server-side templating, and most of the data communication would occur via XHR / JSON requests to something like Web API.  This way, conversion to JSON is a straightforward (automatic) conversion done by MVC (or whatever JSON library you choose), and you don't have to repeat yourself at each layer.  Your model object is just served up as JSON, and Angular now has it.

Efficiency - if we accept this approach, then we have one request for initially loading the view template, and then one request for each time you'd like to load an object and render the template.  As an added bonus, the subsequent calls would only be retrieving the data, and not data + view each time.

Recommendation

To summarise, I think the usage you're describing is already relatively non-standard.  Of course, there's nothing stopping you from using Angular in that fashion, but it's counter productive, and it makes it hard to talk about which approach is better.  I suspect you can simplify your solution greatly by fully embracing Angular's approach, rather than working against it.


问:
Where do you store vendor software images?
Some customization projects require vendor-provided "boxed" software to be installed as a platform. The custom development then consists of creating scripts or development of plug-ins.
The required software packages can easily amount to several gigabytes in size.

I'd like to have all 1st and 3rd party dependencies for a project in a central location. In the end, this means I'd end up putting very large ZIP archives into an artifact repository manager like Nexus, in addition to the custom-developed artifacts.

Is this a good idea? Are there other established practices on where to store vendor-provided software packages - apart from the usual network share?

答:
In my experience the two possibilities you mentioned (a network share or an artifact server) are common. Serving gigabyte-sized files is not a big deal.

Perhaps you might consider what specific functionality you need, in order to choose a method of storing and distributing this software:

Permissions: Can you control who has read and write access?

Versioning: Do you need to store multiple versions?

Metadata: Do you want to store any extra information alongside the files?

Discoverability: Should it be easy to find the files? Do you want to be able to search for the files?

Automation: How easy is it to automate download/installation?


问:
Best OOP pattern to use for creating a commandline SQL API for a proprietary json based company datastore
We need to create a SQL commandline tool for querying a proprietary  json based datastore. I'll be using java. Any suggestions on the primary OOP design pattern I should use for building this API?

I've thought about using the builder pattern in the backend that would compose the json nodes based on statements built up by the builder but that doesn't seem very ground breaking for this use-case.

Could you suggest any other pattern you think would be more useful for this use-case? Also please provide the reason why you think the particular pattern applies.

答:
The Command pattern is usually used in these situations. You can easily create an implementation for each SQL command.

I would suggest to look into CLI frameworks like Spring Shell or Commons CLI.


问:
Android, using a Fragment to hold/edit complex object, accesible from any Activity
I'll do my best to describe the problem, but I'm still very new to several concepts that I think this problem requires to be solved (namely interfaces and threads). I should preface this by saying that I'm obviously not a Comp Sci major (as you'll see). I've learned as I've built my App, therefore my theory is terrible.

My App works as follows: I have a Workout object which is contained in an Activity, which also contains a few UI Fragments. The UI Fragments accept input from the user, Then call methods in the Activity, which then manipulate the object.

After the user finishes inputting their details, the Workout object (Which is a HashMap), gets serialized and passed to the next Activity via Bundle, then deserialized. This generally loses the order in which the user adds exercises to the Workout Object, which is important to maintain. Using LinkedHashMap doesn't work either, as it is bugged when it comes to serialization (It deserializes as a normal HashMap, verified with Eclipse debugger). This whole process happens again when the user wants to save the Workout, as the Workout gets Bundled once again and passed to a Fragment. In other words, the Object is stored, manipulated, and accessed, in the same place as where I handle user input events. This strikes me as terrible practice.

Here's what I think I should do:

Have one Fragment, which contains the Workout Object and runs in the background. It would also be accessible by every Activity which requires the Workout Object, and would communicate with the Fragments and activities via Interface, as follows:

```<code>                                [Background Fragment]
                                /                   \
                               /                     \
                      (Activity 1)                (Activity 2)
                        /       \                 /        \
                 [UI Frag]     [UI Frag]    [UI Frag]    [UI Frag]
</code>```

This solves the issue of having to pass the Workout object around like the only Joint at a Ziggi Marley concert, and the only time it will need to be serialized is when onSaveInstanceState() is called, if I'm not mistaken. This strikes me as better practice.

Does this sound like a reasonable approach for the Data flow of my App?

Although every extra detail you can give me will save me a lot of time, a Yes or No followed by a brief Why would definitely help.

This is more of a bonus question, as I'm fully willing to sort this out through the brute force method, (try things until something works), but:

Given Android's penchant for killing background processes, what implementation would work best for maintaining and manipulating the proposed Background Fragment?

I have a hunch that having this Fragment running on a separate thread might be a good idea, but I know very little about them as of yet. Again, this Fragment needs to be accessible by more than one Activity, pretty much at any time.

答: If your workout object is just a collection of data, why not make it a singleton. Alternatively you could implement it as android Service and start it in your activities. I personally would not implement it as fragment, as for me fragments are more of a UI thing (even although fragments can be headless).</p>


问:
How does whileTrue: works in Smalltalk?
I want to know how whileTrue: works. I searched the implementation that is in BlockClosure:

```<code>whileTrue: aBlock
    ^ [self value] whileTrue: [aBlock value]
</code>```

And another implementation with no parameter:

```<code>whileTrue
    ^ [self value] whileTrue: []
</code>```

But I don't know how that works, that's a recursive method, but this led me to ask several questions:

How does this recursive call terminate?

If [self value] returns a Boolean object, why is whileTrue: not implemented in the Boolean type?

Why is there another implementation named whileTrue that just do not receive any block and evaluates self?

答:
whileTrue: is inlined by the compiler, that's why you don't see the actual implementation. Here's the comment out of Pharo:

"Ordinarily compiled in-line, and therefore not overridable.
      This is in case the message is sent to other than a literal block.
      Evaluate the argument, aBlock, as long as the value of the receiver is true."

If you look at the byte code of #whileTrue: you'll see that the compiler simply uses a jump to make the loop:

```<code>17 <70> self
18 <C9> send: value
19 <9C> jumpFalse: 25
20 <10> pushTemp: 0
21 <C9> send: value
22 <87> pop
23 <A3 F8> jumpTo: 17 <---- here's the jump
25 <7B> return: nil
</code>```

#whileTrue is also inlined directly (slightly optimized byte code).
The inlining is also the reason why there's no implementation of this on Boolean (apart from the fact that there's no point in reevaluating a boolean...).

#whileTrue is there so that you can easily create endless loops the only terminate e.g. when the process terminates, a semaphore is signaled, an exception occurs etc.

Title: How does whileTrue: works in Smalltalk?

Body:
whileTrue: is inlined by the compiler, that's why you don't see the actual implementation. Here's the comment out of Pharo:

"Ordinarily compiled in-line, and therefore not overridable.
      This is in case the message is sent to other than a literal block.
      Evaluate the argument, aBlock, as long as the value of the receiver is true."

If you look at the byte code of #whileTrue: you'll see that the compiler simply uses a jump to make the loop:

17 <70> self
18 <C9> send: value
19 <9C> jumpFalse: 25
20 <10> pushTemp: 0
21 <C9> send: value
22 <87> pop
23 <A3 F8> jumpTo: 17 <---- here's the jump
25 <7B> return: nil

#whileTrue is also inlined directly (slightly optimized byte code).
The inlining is also the reason why there's no implementation of this on Boolean (apart from the fact that there's no point in reevaluating a boolean...).

#whileTrue is there so that you can easily create endless loops the only terminate e.g. when the process terminates, a semaphore is signaled, an exception occurs etc.


问:
Is there a limitation when using the Bloch's Builder Pattern with mandatory fields?
Background

I have a class TextDrawable which draws text on top of a shape. There are a number of properties that can be set while creating a TextDrawable object.

Mandatory Properties:

Text

Shape

Optional Properties:

Color

Width

Height

Font

Border

...

...  etc.

The class will have constructors that look like:

```<code>public TextDrawable(String text, Shape shape) {
}

public TextDrawable(String text, Shape shape, int color) {
}

public TextDrawable(String text, Shape shape, int color, int width, int height) {
}

// and so on..
</code>```

Builder Pattern :

I decided to use the Builder Pattern to make it more convenient to create TextDrawable objects. I followed the design as explained in Effective Java, and here in this highly upvoted answer. I came up with the builder class which will be used as follows:

```<code>TextDrawable drawable = new TextDrawable.Builder("AK", Shape.RECT)
        .width(10)
        .height(10)
        .useFont(Typeface.DEFAULT_BOLD)
        .build();
</code>```

Possible Problem:

There seems to be a problem with this design. Since the "mandatory" fields are passed in the constructor of the builder, the builder cannot be reused.

What if I wanted to create another TextDrawable of same height, width, font etc but with different text and color.  I will have to create another builder object and repeat the same code as above.

```<code>TextDrawable oct = new TextDrawable.Builder("OCT", Shape.RECT)
        .width(10)
        .height(10)
        .useFont(Typeface.DEFAULT_BOLD)
        .build();

TextDrawable nov = new TextDrawable.Builder("NOV", Shape.OVAL)
        .width(10)
        .height(10)
        .useFont(Typeface.DEFAULT_BOLD)
        .build();
</code>```

Proposed Method:

What if I move the mandatory parameters from the constructor of the builder to the build method as follows:

```<code>TextDrawable drawable = new TextDrawable.Builder()
        .width(10)
        .height(10)
        .useFont(Typeface.DEFAULT_BOLD)
        .build("AK", Shape.RECT);
</code>```

This way allows for more flexibility as I can create one instance of the builder and reuse it to create multiple objects. (Also avoids repeating the same code every time I create a new object.) The new usage will look something like:

```<code>TextDrawable.Builder builder = new TextDrawable.Builder()
        .width(10)
        .height(10)
        .useFont(Typeface.DEFAULT_BOLD);

TextDrawable oct = builder.build("OCT", Shape.RECT);
TextDrawable nov = builder.build("NOV", Shape.OVAL);
</code>```

It prevents boilerplate code. Also allows the build method to fit into the fluency idiom as follows:

```<code>TextDrawable oct = builder.buildRect("OCT");
TextDrawable nov = builder.buildOval("NOV");
</code>```

Questions:

Is the problem identified above valid or do I lack understanding of the builder pattern? Should we not reuse builder objects to created multiple instances?

Is the proposed modification to the well known builder pattern valid? Are there any disadvantages of moving the "mandatory fields" into the build() method?

If there are some possible drawbacks, what is a better way of achieving what I want? Should I be using a director object or something that encapsulates the builder to achieve what I want?

答:
1. Is the problem identified above valid or do I lack understanding of the builder pattern? Should we not reuse builder objects to created multiple instances?

It can be, depending on your situation. Here you've identified that you have mandatory fields that are unique, therefore making them parameters to your build method allows you to reuse the same pre-configured builder over and over, which is handy.

2. Is the proposed modification to the well known builder pattern valid? Are there any disadvantages of moving the "mandatory fields" into the build() method?

As far as advantages or disadvantages go, I think that the other option you haven't considered here is allowing the required fields to be set the same way the other fields are. Take the following code for example:

```<code>TextDrawable.Builder builder = new TextDrawable.Builder("OCT", Shape.RECT)
        .width(10)
        .height(10)
        .useFont(Typeface.DEFAULT_BOLD);

// Make the rectangle
TextDrawable oct = builder.build();

// Build the new shape
TextDrawable oct = builder.name("NOV").shape(Shape.OVAL).build();
</code>```

Obviously this is very similar to what you had though, and either approach is equally valid. It really comes down to how much you want to configure, and how much you know will always change. If you'll be building a bunch of rectangles of the same size, but only changing the name, this solution allows you to remove the shape parameter.

3. If there are some possible drawbacks, what is a better way of achieving what I want? Should I be using a director object or something that encapsulates the builder to achieve what I want?

A director would allow you to set up predefined builders more easily. You could have a director for making circles of the same size, or a director that takes in only one length and only makes squares. It's job is to reduce the boilerplate even further, but does so at added class complexity of the overall application. I would really only go this option if you are going to absolutely need it, and stick with your solution of re-using builders where possible.

Body:
1. Is the problem identified above valid or do I lack understanding of the builder pattern? Should we not reuse builder objects to created multiple instances?

It can be, depending on your situation. Here you've identified that you have mandatory fields that are unique, therefore making them parameters to your build method allows you to reuse the same pre-configured builder over and over, which is handy.

2. Is the proposed modification to the well known builder pattern valid? Are there any disadvantages of moving the "mandatory fields" into the build() method?

As far as advantages or disadvantages go, I think that the other option you haven't considered here is allowing the required fields to be set the same way the other fields are. Take the following code for example:

TextDrawable.Builder builder = new TextDrawable.Builder("OCT", Shape.RECT)
        .width(10)
        .height(10)
        .useFont(Typeface.DEFAULT_BOLD);

// Make the rectangle
TextDrawable oct = builder.build();

// Build the new shape
TextDrawable oct = builder.name("NOV").shape(Shape.OVAL).build();

Obviously this is very similar to what you had though, and either approach is equally valid. It really comes down to how much you want to configure, and how much you know will always change. If you'll be building a bunch of rectangles of the same size, but only changing the name, this solution allows you to remove the shape parameter.

3. If there are some possible drawbacks, what is a better way of achieving what I want? Should I be using a director object or something that encapsulates the builder to achieve what I want?

A director would allow you to set up predefined builders more easily. You could have a director for making circles of the same size, or a director that takes in only one length and only makes squares. It's job is to reduce the boilerplate even further, but does so at added class complexity of the overall application. I would really only go this option if you are going to absolutely need it, and stick with your solution of re-using builders where possible.


问:
Overwriting and returning the value of the argument used as conditional of an if statement, inside the same if statement
A simplified example:

```<code>function logTheColor (color){
    if(color == "red"){
        color = "The color is red "
    } else if (color == "yellow") {
        color = "The color is yellow "
    } else {
        color =  "The color is blue"
    }
    console.log(color);
}
</code>```

Is there something wrong with overwriting the value of the variable inside an if statement, if that variable is also part of the if statement condition?  My question is not about the ways I can achieve the same in a "clean" way, I just want to know if it's right although it seems like a bad practice.

  I don't see any problem in this particular case cause I don't have to re-evaluate the "color" variable with the original content again. Am I missing something? Are there cases when it really matters?

答:
For this particular example, for this particular language, it happens to be technically correct.  However, consider this quote from Tony Hoare:

There are two ways to write code: write code so simple there are obviously no bugs in it, or write code so complex that there are no obvious bugs in it.

The problem with your example is you can't look at it and say there are obviously no bugs in it.  I don't write JavaScript code every day, but I've written a few apps that comprise several thousand lines of code each.  I had to write and run a test to determine your example didn't have bugs.

If color were passed by reference, you would have created a bug.

If you were working in a language where a new scope was created inside each conditional block, thereby creating a new variable also named color that went out of scope immediately after being assigned, you would have created a bug.

If a future change ever needs to later use the original color value, you've forced a refactor.

Every single time someone reads your function in the future, they will be expending mental effort keeping the two different colors straight, which makes it that much harder to understand and maintain the code.

Don't make your coding standard the minimum you can get away with and your program works.  Make it so simple there are obviously no bugs in it.


问:
Seeking Guidance on Thread Safe Scripting
I am trying to write a script that will take multiple paths to files on various servers, search them all simultaneously, and return a single list of results to a user. Initially, I was just using Python threads to do this, however I quickly ran into some noted problems:

I wasn't controlling how many threads could be kicked off. So if someone sent 100 files to query for one server, you'd have 100 threads kicked off on that machine, which was bad news.

The results I was getting back were incomplete and varied drastically. If I ran the searches linearly (no threads), I would get complete results, but it would take a long time. I concluded based on this and some personal research that I was not taking a thread-safe approach and began looking into the Queue module.

I've ended up with something like this...

```<code>def worker():
   while q.qsize != 0:
      cmd = q.get()
      # kick off a bash command that zgreps files from different servers
      p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
      results.extend(''.join(p.stdout.readlines()).split('\n')[:-1])
      q.task_done()

NUM_WORKER_THREADS = 10
results = []

q = Queue.Queue()
for i in range(NUM_WORKER_THREADS):
   t = threading.Thread(target=worker)
   t.daemon = True
   t.start()

""" Code to generate input commands needed here """

for c in commands:
   q.put(c)

q.join()

""" Post processing of collected *results* array"""
</code>```

After putting some thread-pool constraints around my program, and also checking in each thread if there is anything still in the queue, my results are inline with what I would expect. After testing, the results match the output of a single threaded approach (except it is much faster).

My questions are as follows:

Is my approach thread-safe? Is there any chance one of the 10 worker threads could overwrite anothers attempt to extend the results array? I am worried that I have just decreased the chance of overwriting to take place, by allocating a smaller thread pool to handle the input, but have not actually solved the problem.

I understand from reading that queues are supposed to be thread-safe. However, when I eliminate thread pools and don't check for the queue size in my threads, I can reproduce the same problem I was having before with large volumes of input. Can someone explain why that is?

答:
1a. Is my approach thread-safe?

No because your results isn't thread safe but is being read and written by many threads. Consider turning this into a Queue as well.

1b. Is there any chance one of the 10 worker threads could overwrite anothers attempt to extend the results array?

Yes, that's exactly what could happen, which is why you should avoid using an array in that manner when threading.

2. I understand from reading that queues are supposed to be thread-safe. However, when I eliminate thread pools and don't check for the queue size in my threads, I can reproduce the same problem I was having before with large volumes of input. Can someone explain why that is?

You really should be using the prebaked Threading Pool to do your work. It should make your life a lot simpler. It takes in a function to call, and a list containing all the variables it should be called with, and then distributes the list of work among the threads. The only catch is that the function you are calling can only be passed one parameter, but since you're only using one you can adapt your code fairly easily

For example:

```<code>from multiprocessing import Pool

def do_work(cmd):
  # kick off a bash command that zgreps files from different server
  # Not sure if this can be done better. Not clear what command you're running
  p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  return ''.join(p.stdout.readlines()).split('\n')[:-1]

NUM_WORKER_THREADS = 10

p = Pool(NUM_WORKER_THREADS)
results = p.map(do_work, commands)
</code>```

As a side note, you can always get around the 1 argument limit by simply packing all your necessary args into a tuple and then unpacking them at the start of the method. Tuples are cheap in python.

For example if you had a function do_work that took two commands as follows:

```<code>def do_work(cmd_one, cmd_two):
  p = subprocess.Popen(cmd_one, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  p2 = subprocess.Popen(cmd_two, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  return ''.join(p.stdout.readlines()) + ''.join(p2.stdout.readlines())
</code>```

we could rewrite it as follows:

```<code>def do_work(commands):
  cmd_one, cmd_two= commands
  p = subprocess.Popen(cmd_one, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  p2 = subprocess.Popen(cmd_two, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  return ''.join(p.stdout.readlines()) + ''.join(p2.stdout.readlines())
</code>```

and change our main method to look like the following:

```<code>from multiprocessing import Pool

NUM_WORKER_THREADS = 10

p = Pool(NUM_WORKER_THREADS)
results = p.map(do_work, [(x, y) for x in command1_list for y in command2_list])
</code>```

In this way, we package both our variables into a tuple for the call, and then immediately unpack them when we need them.

Body:
1a. Is my approach thread-safe?

No because your results isn't thread safe but is being read and written by many threads. Consider turning this into a Queue as well.

1b. Is there any chance one of the 10 worker threads could overwrite anothers attempt to extend the results array?

Yes, that's exactly what could happen, which is why you should avoid using an array in that manner when threading.

2. I understand from reading that queues are supposed to be thread-safe. However, when I eliminate thread pools and don't check for the queue size in my threads, I can reproduce the same problem I was having before with large volumes of input. Can someone explain why that is?

You really should be using the prebaked Threading Pool to do your work. It should make your life a lot simpler. It takes in a function to call, and a list containing all the variables it should be called with, and then distributes the list of work among the threads. The only catch is that the function you are calling can only be passed one parameter, but since you're only using one you can adapt your code fairly easily

For example:

from multiprocessing import Pool

def do_work(cmd):
  # kick off a bash command that zgreps files from different server
  # Not sure if this can be done better. Not clear what command you're running
  p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  return ''.join(p.stdout.readlines()).split('\n')[:-1]

NUM_WORKER_THREADS = 10

p = Pool(NUM_WORKER_THREADS)
results = p.map(do_work, commands)

As a side note, you can always get around the 1 argument limit by simply packing all your necessary args into a tuple and then unpacking them at the start of the method. Tuples are cheap in python.

For example if you had a function do_work that took two commands as follows:

def do_work(cmd_one, cmd_two):
  p = subprocess.Popen(cmd_one, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  p2 = subprocess.Popen(cmd_two, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  return ''.join(p.stdout.readlines()) + ''.join(p2.stdout.readlines())

we could rewrite it as follows:

def do_work(commands):
  cmd_one, cmd_two= commands
  p = subprocess.Popen(cmd_one, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  p2 = subprocess.Popen(cmd_two, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  return ''.join(p.stdout.readlines()) + ''.join(p2.stdout.readlines())

and change our main method to look like the following:

from multiprocessing import Pool

NUM_WORKER_THREADS = 10

p = Pool(NUM_WORKER_THREADS)
results = p.map(do_work, [(x, y) for x in command1_list for y in command2_list])

In this way, we package both our variables into a tuple for the call, and then immediately unpack them when we need them.


答:
My Smalltalk is a bit rusty, and I don't have Smalltalk installed at the moment, so there might be some syntax errors in here, but you get the idea:

```<code>whileTrue: aBlock
    ↑ self value ifTrue: [aBlock value. self whileTrue: aBlock]
</code>```

Here's a version in Ruby that I actually tested, of which the above (I hope) is a translation:

```<code>class Proc
  def vhile(block)
    self.().iff(thn: -> {block.(); vhile(block)})
  end
end
</code>```

You need the following monkeypatches to get the Smalltalk-style conditionals to work:

```<code>class TrueClass
  def iff(thn:, els: ->{})
    thn.()
  end
end

class FalseClass
  def iff(thn:, els: ->{})
    els.()
  end
end
</code>```

Title: How does whileTrue: works in Smalltalk?

Body:
I want to know how whileTrue: works. I searched the implementation that is in BlockClosure:

```<code>whileTrue: aBlock
    ^ [self value] whileTrue: [aBlock value]
</code>```

And another implementation with no parameter:

```<code>whileTrue
    ^ [self value] whileTrue: []
</code>```

But I don't know how that works, that's a recursive method, but this led me to ask several questions:

How does this recursive call terminate?

If [self value] returns a Boolean object, why is whileTrue: not implemented in the Boolean type?

Why is there another implementation named whileTrue that just do not receive any block and evaluates self?

Body:
My Smalltalk is a bit rusty, and I don't have Smalltalk installed at the moment, so there might be some syntax errors in here, but you get the idea:

whileTrue: aBlock
    ↑ self value ifTrue: [aBlock value. self whileTrue: aBlock]

Here's a version in Ruby that I actually tested, of which the above (I hope) is a translation:

class Proc
  def vhile(block)
    self.().iff(thn: -> {block.(); vhile(block)})
  end
end

You need the following monkeypatches to get the Smalltalk-style conditionals to work:

class TrueClass
  def iff(thn:, els: ->{})
    thn.()
  end
end

class FalseClass
  def iff(thn:, els: ->{})
    els.()
  end
end


答:
Here you are recycling a variable in order to not need declare a local variable. The name of the original variable color becomes some notion like color_description. It is bad style to recycle variables, especially for a different entity.

It really is no effort to write:

```<code>var description;
if (color == "red") {
    description = "The color is red ";
} else if (color == "yellow") {
    description = "The color is yellow ";
} else {
    description = "The color is blue";
}
</code>```

Or

```<code>var description =
    color == "red" ? "The color is red "
    : color == "yellow" ? "The color is yellow "
    : "The color is blue";
</code>```

Title: Overwriting and returning the value of the argument used as conditional of an if statement, inside the same if statement

Body:
A simplified example:

```<code>function logTheColor (color){
    if(color == "red"){
        color = "The color is red "
    } else if (color == "yellow") {
        color = "The color is yellow "
    } else {
        color =  "The color is blue"
    }
    console.log(color);
}
</code>```

Is there something wrong with overwriting the value of the variable inside an if statement, if that variable is also part of the if statement condition?  My question is not about the ways I can achieve the same in a "clean" way, I just want to know if it's right although it seems like a bad practice.

  I don't see any problem in this particular case cause I don't have to re-evaluate the "color" variable with the original content again. Am I missing something? Are there cases when it really matters?

Body:
Here you are recycling a variable in order to not need declare a local variable. The name of the original variable color becomes some notion like color_description. It is bad style to recycle variables, especially for a different entity.

It really is no effort to write:

var description;
if (color == "red") {
    description = "The color is red ";
} else if (color == "yellow") {
    description = "The color is yellow ";
} else {
    description = "The color is blue";
}

Or

var description =
    color == "red" ? "The color is red "
    : color == "yellow" ? "The color is yellow "
    : "The color is blue";


问:
Checking that a function is only run from __main__ in Python
I often end up with code files that can either be imported or run as __main__. It's easy to handle this by checking if __name__ == '__main__'. But sometimes if my main function gets too big I split out pieces of it into other functions, expecting that they'll only be called when __name__ == '__main__'. Sometimes I enforce this condition by calling the following assert_main function:

```<code>def assert_main():
    "Use this in a module you only expect to get run as __main__, not imported"
    mod = sys._getframe(1).f_globals["__name__"]
    if "__main__" != mod:
        raise Exception("Module {} is not main".format(mod))
</code>```

Other options would include making assert_main into a decorator or putting the definitions of the functions in question inside of if __name__ == '__main__' block. And there may well be other options I haven't thought of. What is the idiomatically correct thing to do?

答:
What is the idiomatically correct thing to do?

As Martijn pointed out, you really shouldn't care about who calls your code.

That said, the fact that you do care is a smell that your code isn't broken up logically, but rather wherever you feel like splitting up the code.

If your main method is getting too long, look for individual, self contained methods that can be pulled out first. These should be documented well enough that code that imports those scripts can use these methods easily.

If you find yourself writing a lot of command line interfaces and it's this code that you don't want being run from another script, consider putting that into a third file and importing and using it from there. That way anyone who feels that there's value in those methods can use them as easily as you would, and it saves you from re-writing the same thing. You may also be able to find an appropriate python lib to do the same thing for you.


问:
Decimal vs. Integer; Given a fixed range of values, which is preferable for accurate computation?
After getting into a "heated discussion" with someone, I figured I'd ask this question for the sake of posterity.  I'm willing to be corrected if my assumption is incorrect but I'd like to hear a third-party opinion by someone with more credibility than myself.

Let's assume that we need to calculate and store numeric values which are expressed in a decimal format.  However, all numerical inputs and outputs must fit within a specific range of values.  Also, decimals are important but we will never be interested in any value less than a specific decimal place.  This is true for any calculation.  If a calculation results in value containing significant digits under the 10^-8 range, they are essentially 0.  Likewise, if the value is above our upper bound, then this is considered an error-case.

Considering these fixed constraints, which will never change, is it better to use a traditional Decimal(s, p) data type or to use an Integer type that can contain all values represented by shifting the value s-fixed decimal digits to the left?  For instance, for efficiency and accuracy, should we use integers in the range of 0 to 2,100,000,000,000,000  to represent all values between .00000001 and 21,000,000 or should we use decimals defined as (8, 16)?

CLARIFICATION

My specific discussion was regarding data types within MySQL.  I'd prefer a generic response, assuming that most decimal representations are stored in a standardized format.  However, if there is no reliable "standard" for decimal type definitions, consider this question as it relates to MySQL.

答:
Use decimals. Consider

```<code>2.00 * 3.00 = 6.00 (as-is)

200 * 300 = 60000 (hmm: /100)
</code>```

There is no need to think "more optimal" - the computer is likely to do it optimal too. All catches dealt with.

It is especially cumbersome in SQL, to consistently use your own integers correctly, maybe introducing your own function, but at the same time preventing SQL to optimize some queries which would have been column based.

Also consider that at some moment the data must be used in code. And then exactly the same problem repeats itself: multiplication. And automatisms like ORM become more complicated.

Body:
Use decimals. Consider

2.00 * 3.00 = 6.00 (as-is)

200 * 300 = 60000 (hmm: /100)

There is no need to think "more optimal" - the computer is likely to do it optimal too. All catches dealt with.

It is especially cumbersome in SQL, to consistently use your own integers correctly, maybe introducing your own function, but at the same time preventing SQL to optimize some queries which would have been column based.

Also consider that at some moment the data must be used in code. And then exactly the same problem repeats itself: multiplication. And automatisms like ORM become more complicated.


问:
How do you use blank lines in your code?
There has been a few remarks about white space already in discussion about curly braces placements.

I myself tend to sprinkle my code with blank lines in an attempt to segregate things that go together in "logical" groups and hopefully make it easier for the next person to come by to read the code I just produced.

In fact, I would say I structure my code like I write: I make paragraphs, no longer than a few lines (definitely shorter than 10), and try to make each paragraph self-contained.

For example:

in a class, I will group methods that go together, while separating them by a blank line from the next group.

if I need to write a comment I'll usually put a blank line before the comment

in a method, I make one paragraph per step of the process

All in all, I rarely have more than 4/5 lines clustered together, meaning a very sparse code.

I don't consider all this white space a waste because I actually use it to structure the code (as I use the indentation in fact), and therefore I feel it worth the screen estate it takes.

For example:

```<code>for (int i = 0; i < 10; ++i)
{
    if (i % 3 == 0) continue;

    array[i] += 2;
}
</code>```

I consider than the two statements have clear distinct purposes and thus deserve to be separated to make it obvious.

So, how do you actually use (or not) blank lines in code ?

答:
I only use whitespaces within a function/method to separate declarations and code.

If you feel the need to have some lines to separate sub-blocks of code implementing some logic, then they should be but in another function/private method. It's up to your compiler to not make that too big an overhead.

typically, in peusdo-code:

```<code>def function(arg1, argn, ...)
    INITIALIZERS

    CODE
    BLOCK_START
        INITIALIZERS

        CODE
    BLOCK_END
    CODE
end
</code>```

If I see useless whitespace, I usually cringe.

Body:
I only use whitespaces within a function/method to separate declarations and code.

If you feel the need to have some lines to separate sub-blocks of code implementing some logic, then they should be but in another function/private method. It's up to your compiler to not make that too big an overhead.

typically, in peusdo-code:

def function(arg1, argn, ...)
    INITIALIZERS

    CODE
    BLOCK_START
        INITIALIZERS

        CODE
    BLOCK_END
    CODE
end

If I see useless whitespace, I usually cringe.

ContentLicense: CC BY-SA 2.5


问:
Sharing business logic between server-side and client-side of web application?
Quick question concerning shared code/logic in back and front ends of a web application.

I have a web application (Rails + heavy JS) that parses metadata from HTML pages fetched via a user supplied URL (think Pinterest or Instapaper). Currently this processing takes place exclusively on the client-side. The code that fetches the URL and parses the DOM is in a fairly large set of JS scripts in our Rails app.

Occasionally want to do this processing on the server-side of the app. For example, what if a user supplied a URL but they have JS disabled or have a non-standard compliant browser, etc. Ideally I'd like to be able to process these URLS in Ruby on the back-end (in asynchronous background jobs perhaps) using the same logic that our JS parsers use WITHOUT porting the JS to Ruby.

I've looked at systems that allow you to execute JS scripts in the backend like execjs as well as Ruby-to-Javascript compilers like OpalRB that would hopefully allow "write-once, execute many", but I'm not sure that either is the right decision.

Whats the best way to avoid business logic duplication for apps that need to do both client-side and server-side processing of similar data?

答:
Whats the best way to avoid business logic duplication for apps that need to do both client-side and server-side processing of similar data?

Yes, this is possible. I've used node.js on the server, and this is why I tell everyone to use it. It will come a day you need your client side stuff on the server and viceversa... Currently I thing twice before adding something only to the server side part of the app.

I use the require.js module system on both of the client and server side.


问:
Decorator Pattern: can it solve issues arising from changes to underlying code?
I understand that decorators solve the problem of needing to mix and match behaviors, but it was suggested that I could use the decorator pattern to solve issues of brittleness that might arise due to changes in the underlying base code.

Specifically, Microsoft provides an ActiveDirectoryMembershipProvider that has virtual methods for creating and updating users. The update method doesn't update all the information that we'd like to update so I felt we should create a new class that inherits from the ActiveDirectoryMembershipProvider so that we could call the base implementation and then write code to update the extended information that the base implementation doesn't cover.

But it was suggested that because the ActiveDirectoryMembershipProvider is 3rd party code, we might run into issues that could be solved by the decorator pattern. It doesn't seem to me that any issues that arise from changes in the underlying code could be mitigated by the decorator pattern. Am I missing anything here?

答:
Repeat after me - Patterns are not always the answer

Phew. Now that we've gotten that out of the way, lets move on. First off, anytime you're extending 3rd party code that doesn't make any guarantees to lifespan or function declarations, you're asking for a nightmare when updating that 3rd party code. A method could change it's parameters, or the class may be removed all together, leaving your code now empty and lonely.

The decorator pattern is great at allowing you to granularly modify small pieces of the underlying method but isn't the end-all be-all solution you may think it is. If you need to add an entire pattern and all the ceremony that comes with it to modify one little variable, why not just make a method that does just that. You don't need it to be hyper extensible or worry about what qualities the pattern has. Just do what you need to do without all the extra overhead.


答:
I agree with @Ampt's answer.

I would add another argument here.

Note that you can only ever inherit from one class - I mean, in most popular languages, which happens to include C#. (And even in those where it is possible, such as C++, it is adviced to use this possibility sparringly).

So by making your class extend ActiveDirectoryMembershipProvider, you are effectively blocking it from extending any other class, or incorporating it into any custom class hierarchy that you have in place.

Composition (based on delegation) beats inheritance in terms of flexibility, decorator or not.

Another factor is testability. If you create a decorator that enwraps ActiveDirectoryMembershipProvider, it may be easier to substitute it with a dummy object for testing purposes.

Title: Decorator Pattern: can it solve issues arising from changes to underlying code?

Body:
I understand that decorators solve the problem of needing to mix and match behaviors, but it was suggested that I could use the decorator pattern to solve issues of brittleness that might arise due to changes in the underlying base code.

Specifically, Microsoft provides an ActiveDirectoryMembershipProvider that has virtual methods for creating and updating users. The update method doesn't update all the information that we'd like to update so I felt we should create a new class that inherits from the ActiveDirectoryMembershipProvider so that we could call the base implementation and then write code to update the extended information that the base implementation doesn't cover.

But it was suggested that because the ActiveDirectoryMembershipProvider is 3rd party code, we might run into issues that could be solved by the decorator pattern. It doesn't seem to me that any issues that arise from changes in the underlying code could be mitigated by the decorator pattern. Am I missing anything here?


问:
Do objects with validation logic in their domain really represent their real world counterparts?
I asked a question about whether validation behavior should be treated the same as other types of behavior in regard to the concept of OOP being "data + behavior". I got some good answers back that addressed the question from the philosophical point of view and confirmed that the answer to that question seems to be yes.

Now I'd like to address this question from a different angle: Shouldn't objects represent their real world counterparts?

Suppose I give a paper form to someone to fill out. They can pencil in the fields on the form in any order they'd like to and they can even fill in all sorts of incorrect values. When they turn the paper in to me I, representing a broker, may hand it back to them and tell them I can't file it until they fix any invalid entries though.

There's also a comparison to be made between the format of the questions on the paper and a user interface that validates input. Maybe you put checkboxes on the paper and instruct the person to only select one. Of course software can get a lot fancier with this type of validation than a physical sheet of paper, but let's be clear that this type of validation is all in the user interface... validation in the 'domain' simply doesn't exist in the physical realm for this type of object.

Is the paper going to crumple itself up or catch on fire if you write something invalid on it?

So my question is this: if a physical piece of paper has no inherit ability to validate itself, then why would this behavior belong in the domain?

答:
Whether it is with paper or highly validated electronic data gathering, discrepancies can come up between how things are thought to be done by some (management) and how it is really done in the field.

You may develop a different set of domain rules depending on how the requirements are gathered.

Model based on the form. A supervisor hands you a blank copy of a paper form and instructs you to "make it exactly like this one." The instructions indicate "select only one" so you code it accordingly.

Model based on usage. The person in charge of reviewing and tallying the data gives you a stack of completed forms. You notice some dates entered as month/year because no one remembers the exact day and nor do they care. They select more than one item in the restricted area because everyone has determined that a pair of values is more accurate (How long would it take to get that feedback in a restricted system?). People make comments on the back and enter other notes in the margins.

A developer could find themselves in either scenario and would build what the client "wanted" but you may find you haven't built what they needed. The supervisor may have recognized the inexact dates and wants to force a more precise one (That's why we hired you.) or they see the comments and decide to add that even though it is not on the form. You'll rarely be right the first time. Users will change the rules (And in business they're not always logical).

You may find yourself creating a hybrid of two real world models because it is possible in the computer. The real world model tends to get so complex, no one can tell you what it is; you're better off tackling small pieces of it at a time, being very rigid at first but understanding you may have to loosen things up and be prepared for a lot of change.

Business models (or any others involving people) and the perception/interpretation of the model and domain constantly evolve, so there probably is never a point where they really match.


答:
Dealing with some "manage project from start to end"-type intranet applications, I believe it can be very valuable to separately-capture what different remote systems or users told my system they thought was true, versus the mix of data my system has currently decided to believe and honor.

This leads to systems where you store and act upon things like "submissions" (pending, succeeded, failed, archived) or "events" (AddressChangeRequested), rather than CRUD-ish take-it-or-leave-it modification.

While it adds a layer of abstraction, it also makes it easier to handle weird stuff the business insists on keeping, like allowing certain contradictions, or applying certain changes "retroactively" from a later point in the task lifecycle.

Title: Do objects with validation logic in their domain really represent their real world counterparts?

Body:
I asked a question about whether validation behavior should be treated the same as other types of behavior in regard to the concept of OOP being "data + behavior". I got some good answers back that addressed the question from the philosophical point of view and confirmed that the answer to that question seems to be yes.

Now I'd like to address this question from a different angle: Shouldn't objects represent their real world counterparts?

Suppose I give a paper form to someone to fill out. They can pencil in the fields on the form in any order they'd like to and they can even fill in all sorts of incorrect values. When they turn the paper in to me I, representing a broker, may hand it back to them and tell them I can't file it until they fix any invalid entries though.

There's also a comparison to be made between the format of the questions on the paper and a user interface that validates input. Maybe you put checkboxes on the paper and instruct the person to only select one. Of course software can get a lot fancier with this type of validation than a physical sheet of paper, but let's be clear that this type of validation is all in the user interface... validation in the 'domain' simply doesn't exist in the physical realm for this type of object.

Is the paper going to crumple itself up or catch on fire if you write something invalid on it?

So my question is this: if a physical piece of paper has no inherit ability to validate itself, then why would this behavior belong in the domain?


问:
Designing classes the right way
I am trying to design my classes in the optimal way for the following scenario.
A city has metro lines covering a number of stations.There are 4 lines represented by 4 colors.The user has to enter start and end stations and we should return the shortest route to take and cost of travel.The cost is constant from one station to adjacent station- $2.If they need to switch lanes then additional $1 needs to be paid.

Here are the classes and methods I have designed for this.

Is this a good design? What improvements can be made to this for it to be reusable and robust?What object oriented principles can be applied to make this design better?

here is link to my class diagram, if the above one is not clear https://creately.com/diagram/i1ay21xi2/55WPjrH3iHFsDyi8Bs6sZgTDksw%3D

答:
Basically a Subway network is a collection of line, a line is a collection of stations and a station a collection of intersections (1 or more other stations connected) .

You could have your Subway network represented by a basic hashMap with all your lines.

Your stations could be modeled as a collection of intersection/sequences

```<code>Subway network
 - Lines (hashMap could do it)

Line
 - Stations (hashMap could do it)

Station
 - Intersections (hashMap could do it)

Intersection (structured as a 2 sided linked list)
 - line
 - previous station
 - next station
</code>```

Considering your object model as you presented it, you should avoid using profusely get/set or you will end un with an anemic model.

Your methods should look like:

Line::calculateTravelPrice(Station1, Station2)

Line::intersects(line)

Station::isEndOfLine()

Basically you let each component do to what it's made for.

You will have to think more about your specific domain and what you need to be able to do, but this answer might be a nice beginning

Title: Designing classes the right way

Body:
Basically a Subway network is a collection of line, a line is a collection of stations and a station a collection of intersections (1 or more other stations connected) .

You could have your Subway network represented by a basic hashMap with all your lines.

Your stations could be modeled as a collection of intersection/sequences

Subway network
 - Lines (hashMap could do it)

Line
 - Stations (hashMap could do it)

Station
 - Intersections (hashMap could do it)

Intersection (structured as a 2 sided linked list)
 - line
 - previous station
 - next station

Considering your object model as you presented it, you should avoid using profusely get/set or you will end un with an anemic model.

Your methods should look like:

Line::calculateTravelPrice(Station1, Station2)

Line::intersects(line)

Station::isEndOfLine()

Basically you let each component do to what it's made for.

You will have to think more about your specific domain and what you need to be able to do, but this answer might be a nice beginning


问:
Is it better to create thread safe subclasses or make the main class thread safe?
Say we have a class that is frequently used in a single-thread context:

```<code>public class Foo
{
    public List<Bar> Data;

    public virtual void ChangeData()
    {
        for(var i =0; i < Data.Count; i++)
        {
            if(i % 4 == 0)
            {
                data[i].Baz();
            }
        }
    }
}
</code>```

If we were to decide we wanted to use the thread in a multi-threaded context (in addition to its current single-threaded usage), are there advantages (assuming it has full unit test coverage) to making a thread-safe subclass 'ThreadSafeFoo' vs. altering 'Foo' to be thread safe?

I was wondering about this because there are specific subclasses in System.Collections that are intended to be used across threads, and I wanted to know whether there was a reason this thread-safety wasn't simply rolled into List, etc.

答:
The problem with this kind of thinking is that you often can't just make a class thread-safe (at least not in a way that is useful), without also modifying how it works. And collections demonstrate this nicely: for example, using normal Dictionary, you could implement some kind of caching like this:

```<code>if (!dictionary.ContainsKey(key))
    dictionary.Add(key, GetValue(key));

return dictionary[key];
</code>```

But such code wouldn't work well in a multi-threaded environment, even if there was a version of Dictionary with ContainsKey(), Add() and the indexer that are thread-safe.

Instead, using ConcurrentDictionary (with is not a subclass of Dictionary), you could write the same code like this:

```<code>return dictionary.GetOrAdd(key, GetValue);
</code>```

But you usually don't need to go that far to achieve thread-safety, the right way of using a lock is enough:

```<code>lock (dictionary)
{
    if (!dictionary.ContainsKey(key))
        dictionary.Add(key, GetValue(key));

    return dictionary[key];
}
</code>```

But this means using the type in a thread-safe way, not changing it or creating a subclass.

Body:
The problem with this kind of thinking is that you often can't just make a class thread-safe (at least not in a way that is useful), without also modifying how it works. And collections demonstrate this nicely: for example, using normal Dictionary, you could implement some kind of caching like this:

if (!dictionary.ContainsKey(key))
    dictionary.Add(key, GetValue(key));

return dictionary[key];

But such code wouldn't work well in a multi-threaded environment, even if there was a version of Dictionary with ContainsKey(), Add() and the indexer that are thread-safe.

Instead, using ConcurrentDictionary (with is not a subclass of Dictionary), you could write the same code like this:

return dictionary.GetOrAdd(key, GetValue);

But you usually don't need to go that far to achieve thread-safety, the right way of using a lock is enough:

lock (dictionary)
{
    if (!dictionary.ContainsKey(key))
        dictionary.Add(key, GetValue(key));

    return dictionary[key];
}

But this means using the type in a thread-safe way, not changing it or creating a subclass.


问:
Business Logic vs Presentation/View Logic
I often question myself of where to put the logic that organize the data to a view that is not necessarily a business logic in a 3-layered architecture (DAO, Business, View).

I'll put an example to be clearer:

I have a UI in my aplication that shows pending tickets and answered tickets in two different tabs. To get the data from the database, I make a single query. Since there is no business logic, I'm returning the whole list to the Controller (View) and separating it in two lists to pass to the view template.

Should I be separating this in the business layer? Or is it correct to separate in the controller, since the logic is attached to that single UI?

答:
I like where you are going with this curiosity, so I'm going to bring up something else I see.

To follow not only "Separation of Concerns", but also "Persistence Ignorance", it is almost always a Very Bad Idea to allow your UI layer to call into your business/data side with a "Get All" (Or even close) method.  I realize there may be a constraint or two like Where UserId == LoggedInUser, but that is still too close.

The reason being, suddenly you have clever UI Developers using the "Get All" method, and performing business/Data-Access logic on the UI to separate out information, pick and filter through, etc.

Even if you tell yourself that will never happen, or that you're the only one in the next 100 years that will touch this code and you Promise yourself you'll never do that, you still shouldn't open the UI up to such power.

Now imagine some time in the future a single UI Control needs to display JUST the Answered (or pending) tickets.  What do you do now?  You have to "Get All" and perform your filtering logic on the UI side?

I wouldn't even put that into the Business Logic.  This is about data separation.  You should have as finite queries as possible in your Data-Access layer, and expose only those required results to your Business Logic.  Your Business Logic in this case may just be a wrapper to return a Data-Access result, but that's okay.  That's the BLL's responsibility to determine the Persistence object and route calls.

Now, if you need a list on your UI side that shows "All" Tickets for a user, it may be prudent to have that "Get All" method where the only filter is the UserId.  However, it may be more prudent to combine the Pending and Answered Queries.  Why?

What if in the future you add a "Deleted", "Removed", "In-Flux", "New" or any other kind of status?  Now you have to re-write code because all you wanted to do is show a Combined List of Pending and Answered questions.

So give your UI less control over massive lists, and instead allow it to pull back only the limited information it needs, and alter/combine from there.


答:
For database storage, decimals.

TL;DR Backstory

If you were processing these results primarily in main memory, it might be a toss-up. There are many small-range floating point / decimal problems that can be solved with scaled integers and fixed point math. For example, I solved this this recent partitioning problem from Stack Overflow in the integer realm, then returned the answer as floating point. I've also seen many text formatting and graphical layout algorithms use similar approximations. The integer math is simple, very fast, and works well.

But, without further constraining your use case, there are drawbacks, such as it becoming your responsibility to

Provide any mathematic functions like sin and sqrt you might need.

Convert from your custom-scaled integers to other types you might need, like formatting into strings, or into floats and proper decimal types.

Those are "a simple matter of effort," but the details of getting those things right can be vexing and distract you from your primary coding goals.

Add to this that you are specifically interested in storing these values in a database. That implies permanence and a long data lifetime. If there's anything we've learned about fixed-precision data in this industry, it's that requirements will change over time, and then you'll have to change your data, and the apps that use them. Think Y2K or financial market decimalization. Fixed-point seems a solid foundation, but in a few years your decimal precision needs might change. The scale chosen for printer internals when 300dpi printers seemed impossibly high-resolution wasn't so precise when 1200- and 2400-dpi printers rolled in a few years later.

So, if you're interested in efficient in-memory representations fitted to specific problems, fixed-point can work well. But if you're storing data over time, decimals make for a richer, more future-proofed representation that someone else takes the responsibility for making work, getting you back to your own development tasks.

Title: Decimal vs. Integer; Given a fixed range of values, which is preferable for accurate computation?

Body:
After getting into a "heated discussion" with someone, I figured I'd ask this question for the sake of posterity.  I'm willing to be corrected if my assumption is incorrect but I'd like to hear a third-party opinion by someone with more credibility than myself.

Let's assume that we need to calculate and store numeric values which are expressed in a decimal format.  However, all numerical inputs and outputs must fit within a specific range of values.  Also, decimals are important but we will never be interested in any value less than a specific decimal place.  This is true for any calculation.  If a calculation results in value containing significant digits under the 10^-8 range, they are essentially 0.  Likewise, if the value is above our upper bound, then this is considered an error-case.

Considering these fixed constraints, which will never change, is it better to use a traditional Decimal(s, p) data type or to use an Integer type that can contain all values represented by shifting the value s-fixed decimal digits to the left?  For instance, for efficiency and accuracy, should we use integers in the range of 0 to 2,100,000,000,000,000  to represent all values between .00000001 and 21,000,000 or should we use decimals defined as (8, 16)?

CLARIFICATION

My specific discussion was regarding data types within MySQL.  I'd prefer a generic response, assuming that most decimal representations are stored in a standardized format.  However, if there is no reliable "standard" for decimal type definitions, consider this question as it relates to MySQL.


问:
Name for this type of parser, OR why it doesn't exist
Conventional parsers consume their entire input and produce a single parse tree.  I'm looking for one that consumes a continuous stream and produces a parse forest [edit: see discussion in comments regarding why this use of that term may be unconventional].  My gut says that I can't be the first person to need (or think I need) such a parser, but I've searched off and on for months to no avail.

I recognize that I may be ensnared by the XY problem.  My ultimate purpose is to parse a stream of text, ignoring most of it, and produce a stream of parse trees from the sections that are recognized.

So my question is conditional: if a class of parsers with these characteristics exists, what is it called?  And if not, why not?  What is the alternative?  Perhaps I'm missing some way I can make conventional parsers do what I want.

答:
Far from ideal, but I've seen it done more than once: at each input line try to parse.  if fails, keep the line and add the next one.  In pseudocode:

```<code>buffer = ''
for each line from input:
    buffer = buffer + line
    if can parse buffer:
        emit tree
        buffer = ''
</code>```

The big problem is that in some languages you can't know if an expression is complete before reading the next line.  In that case, you it seems that you could read the next one, and check if it's a valid beginning, or a valid continuation... But for that you need the exact language syntax

Worse, in those languages it's not hard to create a pathological case that can't be parsed until the end of file, even if it wasn't a single long statement.

Body:
Far from ideal, but I've seen it done more than once: at each input line try to parse.  if fails, keep the line and add the next one.  In pseudocode:

buffer = ''
for each line from input:
    buffer = buffer + line
    if can parse buffer:
        emit tree
        buffer = ''

The big problem is that in some languages you can't know if an expression is complete before reading the next line.  In that case, you it seems that you could read the next one, and check if it's a valid beginning, or a valid continuation... But for that you need the exact language syntax

Worse, in those languages it's not hard to create a pathological case that can't be parsed until the end of file, even if it wasn't a single long statement.


答:
A parser that returns a (partial) result before the whole input has been consumed is called an incremental parser. Incremental parsing can be difficult if there are local ambiguities in a grammar that are only decided later in the input. Another difficulty is feigning those parts of the parse tree that haven't been reached yet.

A parser that returns a forest of all possible parse trees – that is, returns a parse tree for each possible derivation of an ambiguous grammar – is called … I'm not sure if these things have a name yet. I know that the Marpa parser generator is capable of this, but any Earley or GLR based parser should be able to pull this off.

However, you don't seem to want any of that. You have a stream with multiple embedded documents, with garbage in between:

```<code> garbagegarbage{key:42}garbagegarbage[1,2,3]{id:0}garbage...
</code>```

You seem to want a parser that skips over the garbage, and (lazily) yields a sequence of ASTs for each document. This could be considered to be an incremental parser in its most general sense. But you'd actually implement a loop like this:

```<code>while stream is not empty:
  try:
    yield parse_document(stream at current position)
  except:
    advance position in stream by 1 character or token
</code>```

The parse_docment function would then be a conventional, non-incremental parser. There is a minor difficulty of ensuring that you have read enough of the input stream for a successful parse. How this can be handled depends on the type of parser you are using. Possibilities include growing a buffer on certain parse errors, or using lazy tokenization.

Lazy tokenization is probably the most elegant solution due to your input stream. Instead of having a lexer phase produce a fixed list of tokens, the parser would lazily request the next token from a lexer callback[1]. The lexer would then consume as much of the stream as needed. This way, the parser can only fail when the real end of the stream is reached, or when a real parse error occurred (i.e. we started parsing while still in garbage).

[1] a callback-driven lexer is a good idea in other contexts as well, because this can avoid some problems with longest-token matching.

If you know what kind of documents you are searching for, you can optimize the skipping to stop only at promising locations. E.g. a JSON document always begins with the character { or [. Therefore, garbage is any string that does not contain these characters.

Title: Name for this type of parser, OR why it doesn't exist

Body:
Conventional parsers consume their entire input and produce a single parse tree.  I'm looking for one that consumes a continuous stream and produces a parse forest [edit: see discussion in comments regarding why this use of that term may be unconventional].  My gut says that I can't be the first person to need (or think I need) such a parser, but I've searched off and on for months to no avail.

I recognize that I may be ensnared by the XY problem.  My ultimate purpose is to parse a stream of text, ignoring most of it, and produce a stream of parse trees from the sections that are recognized.

So my question is conditional: if a class of parsers with these characteristics exists, what is it called?  And if not, why not?  What is the alternative?  Perhaps I'm missing some way I can make conventional parsers do what I want.

Body:
A parser that returns a (partial) result before the whole input has been consumed is called an incremental parser. Incremental parsing can be difficult if there are local ambiguities in a grammar that are only decided later in the input. Another difficulty is feigning those parts of the parse tree that haven't been reached yet.

A parser that returns a forest of all possible parse trees – that is, returns a parse tree for each possible derivation of an ambiguous grammar – is called … I'm not sure if these things have a name yet. I know that the Marpa parser generator is capable of this, but any Earley or GLR based parser should be able to pull this off.

However, you don't seem to want any of that. You have a stream with multiple embedded documents, with garbage in between:

 garbagegarbage{key:42}garbagegarbage[1,2,3]{id:0}garbage...

You seem to want a parser that skips over the garbage, and (lazily) yields a sequence of ASTs for each document. This could be considered to be an incremental parser in its most general sense. But you'd actually implement a loop like this:

while stream is not empty:
  try:
    yield parse_document(stream at current position)
  except:
    advance position in stream by 1 character or token

The parse_docment function would then be a conventional, non-incremental parser. There is a minor difficulty of ensuring that you have read enough of the input stream for a successful parse. How this can be handled depends on the type of parser you are using. Possibilities include growing a buffer on certain parse errors, or using lazy tokenization.

Lazy tokenization is probably the most elegant solution due to your input stream. Instead of having a lexer phase produce a fixed list of tokens, the parser would lazily request the next token from a lexer callback[1]. The lexer would then consume as much of the stream as needed. This way, the parser can only fail when the real end of the stream is reached, or when a real parse error occurred (i.e. we started parsing while still in garbage).

[1] a callback-driven lexer is a good idea in other contexts as well, because this can avoid some problems with longest-token matching.

If you know what kind of documents you are searching for, you can optimize the skipping to stop only at promising locations. E.g. a JSON document always begins with the character { or [. Therefore, garbage is any string that does not contain these characters.


问:
Implicit Conversion Operators for Value Types in C#
I’ve come across this blog article: Implicit Conversion Operators are Bad. The article discourages the use of implicit conversion with reference types. The article describes problems caused by implicit conversions of reference types, which boils down to the following

[...] main question of this post: why are implicit conversion operators bad on reference types?
  [...] By adding an implicit conversion operator to a reference type, you have now introduced value semantics to assignments – but only from one type to another.

  [emphasis original]

My question, however, is about value types.  In the beginning, the article has got this statement:

Implicit conversion operators are incredibly important to the language, but only for value types.

  [emphasis original]

The article doesn’t go into details on how to use implicit conversion with value types.  That is what I’m wondering about.  Here's my present thinking:

The conversion operator is on a value type, and it returns a value type.  Implicit - okay.

The conversion operator is on a reference type, and it returns a value type.  Implicit – okay.

The conversion operator is on a value type, and it returns a reference type.  (That would be a somewhat bizarre, but would it be wrong?)  Implicit – not okay.

The conversion operator is on a reference type, and it returns a reference type.  Implicit – not okay.

In a more compact form:

If it returns a value type, an implicit conversion operator is okay on both value type and reference type.

If it returns a reference type, implicit conversion is not okay.

Is this correct?  Is this complete?

p.s.  For the most part, I work mostly with C and C++, where I have fine control over things like const, pointers, references.  Of course, that comes at a risk of contracting nasty pointer-related bugs.

答:
The short answer is that implicit operators are mostly about math.

All other things being equal, method calls are easier to read, easier to maintain, and easier to reason about, for non-math operations.  Operators work with math because they are well understood; everyone knows what an addition operation is and what operator represents it.  And when it's not being used in a math context (i.e. string concatenation), it still makes perfect sense semantically.

In the absence of math operations (i.e. reference types), operators work best when they are part of the language proper.  The Lambda Expression operator in C# => is part of the language specification, is well-understood, and covers a broad variety of use cases.  But it doesn't mean the same thing in other languages, like the + operator usually does.


答:
There isn't one specific name for a parser that does this. But I will highlight one algorithm that does this: parsing with derivatives.

It consumes input, one token at a time. It will produce a parse forest at the end of input. Alternatively, you can also get the whole parse forest while in the middle of parsing (a partial parse).

Parsing with derivatives handles context-free grammars, and will produce a parse forest for ambiguous grammars.

It's an elegant theory, really, but is only in its infancy, and isn't widely deployed. Matt Might has a list of links to various implementations in Scala/Racket/etc.

The theory is easier to learn if you start with recognition with derivatives (that is, start with taking derivatives of languages, with the goal of recognizing some input to determine whether it's valid or not), and then alter the program to parse with derivatives (that is, change it so instead of taking derivatives of languages, it takes derivatives of parsers, and computes a parse forest).


问:
Runtime analysis of functions that call other functions
If you have a function being called in another function, do you figure out the runtime for the being called and then "add" that to function you wish to analyze the runtime for?

Function to be analyzed:

```<code>for (i = 0, i > n, ++i)
{
    if (function.call() > 0)
    {
        \\something
    }
}
</code>```

Function called:

```<code>Call
{
   for (i = 0, i > n, ++i)
    {
        \\return something
    }
}
</code>```

答:
Think of it as some kind of accounting.

The inclusive time of a function is:

The elapsed time between the entrance and the exit of this function,

MINUS pure overhead (if known; zero if negligible or undetermined)

PLUS total elapsed time spent on other CPU cores or OS threads due to any work that is delegated by this function. (In other words, external work that is "billable" to this function.)

The exclusive time of a function is:

The inclusive time of the function,

MINUS the total inclusive time of all children of that function.

The definition of "children" is up to the profiler designer.

For example, child functions which have been completely inlined into the parent function are usually no longer considered to be a separate item, and thus will not be subtracted.

On the other hand, any use of "source-based" profiler frameworks will impede the inlining optimization by the compiler, to the point that any functions marked for instrumentation will never be inlined anyway.


问:
Ensure scheduled event only runs once a day?
In a hobby project of mine, a "smart home" for controlling lights, I'm planning to create a feature which turns off all lights at a given time of day. There are also several other features which runs on command.

I've created a stack of events which are checked on an interval of (n) seconds. The program simply iterates trough each event in the stack, asks them to evaluate if they should be run, and then continues.

For the "on command" events I simply discard the event out of the stack after they're ran.

However for my planned feature I need the event to evaluate itself, run if the time of day is correct, and then go back into the stack - without firing again on the next iteration.

My problems is that I can't tell the event to run exactly at (for example) 12:00:00 as the interval for checking events isn't that exact (this may indicate other problems in my logic?). Neither can I use a flag to indicate that the event has ran, as it is supposed to run again the next day (in 24hrs).

To give some context: The idea behind the event stack is to provide a queue for incoming commands which are coming trough a REST Service (with multiple users).

Update: A possible solution may simply be to reschedule the task after it's completed. However I'm leaving the question open a bit longer in case someone has an alternate solution.

答: So if you're having problems getting it to run at an exact time, give it an interval to run, say from 12:00:00 -> 12:05:00 and once it runs inside that period, set a flag. Then, in another period, say, from 12:05:00 -> 12:10:00 check for that flag and clear it so that you can run it again in 24 hours. you can change these periods or move them to make them work for your timing needs (maybe make them hours instead of 5 minutes)</p>


答:
Why don't you just use Timer.scheduleAtFixedRate(TimerTask task, Date firstTime, long period)

If you set firstTime to currenttime rounded up to next minute, the timer will run at 12:00 if you set period to 60000

Title: Ensure scheduled event only runs once a day?

Body:
In a hobby project of mine, a "smart home" for controlling lights, I'm planning to create a feature which turns off all lights at a given time of day. There are also several other features which runs on command.

I've created a stack of events which are checked on an interval of (n) seconds. The program simply iterates trough each event in the stack, asks them to evaluate if they should be run, and then continues.

For the "on command" events I simply discard the event out of the stack after they're ran.

However for my planned feature I need the event to evaluate itself, run if the time of day is correct, and then go back into the stack - without firing again on the next iteration.

My problems is that I can't tell the event to run exactly at (for example) 12:00:00 as the interval for checking events isn't that exact (this may indicate other problems in my logic?). Neither can I use a flag to indicate that the event has ran, as it is supposed to run again the next day (in 24hrs).

To give some context: The idea behind the event stack is to provide a queue for incoming commands which are coming trough a REST Service (with multiple users).

Update: A possible solution may simply be to reschedule the task after it's completed. However I'm leaving the question open a bit longer in case someone has an alternate solution.


问:
Is not being able to resolve a function call to its declaration a drawback of Polymorphism?
Consider a class that prints an "outline" table for a particular product line.  Say you have several, A, B, C, D.  The mechanism of the table generation is the same, but the data is different.  I could create a "base" class called OutlineTableGenerator, and one class per product line each that extend that base class.  I can put data getters into individual product classes and let the base class operate on the data.  Observe below:

```<code>class OutlineTableGenerator
{
    protected $vars;

    function __construct($vars)
    {
        $this->vars = $vars;
    }

    public function getOutlineTable()
    {
        $data = $this->getOutlineTableData();  //my question is about this line
    }
}
</code>```

and

```<code>class OutlineTableGeneratorForProductA extends OutlineTableGenerator
{
    function __construct($vars)
    {
        parent::__construct($vars);
    }

    protected function getOutlineTableData()
    {
         return ['data' => $this->vars['stuff']];
    }
}
</code>```

See line $data = $this->getOutlineTableData();.  My problem with this line is that my IDE, nor any other IDE for that matter, will be able to figure out which class & function it will resolve to at run time.  I quite frequently use a feature to jump from the line in the code where a function is called, to the actual function declaration.  In this case, I using that feature on the line in question will not jump to function declaration.  Because there are several of those, and nor IDE nor programming language itself knows which function I want.  I think this is bad.

Is there a work-around?  Is this a drawback of polymorphism in OO?  How do YOU live with it?

答:
A failure in polymorphism? I guess that depends on how you use the classes.

Do you ever instantiate an OutlineTableGenerator object? Because I would expect any such object to cause a fatal error if its getOutlineTable method is ever called.

It looks like you really have an abstract class there; one which is never instantiated directly, but can be extended and also used for type hinting within parameter lists.

```<code>abstract class OutlineTableGenerator {
   ...
    public function getOutlineTable() {
        $data = $this->getOutlineTableData(); //my question is about this line
   }

    abstract function getOutlineTableData();
}
</code>```

My IDE will usually then offer me a list of implementations whenever I follow the reference for such an abstract function call.

Body:
A failure in polymorphism? I guess that depends on how you use the classes.

Do you ever instantiate an OutlineTableGenerator object? Because I would expect any such object to cause a fatal error if its getOutlineTable method is ever called.

It looks like you really have an abstract class there; one which is never instantiated directly, but can be extended and also used for type hinting within parameter lists.

abstract class OutlineTableGenerator {
   ...
    public function getOutlineTable() {
        $data = $this->getOutlineTableData(); //my question is about this line
   }

    abstract function getOutlineTableData();
}

My IDE will usually then offer me a list of implementations whenever I follow the reference for such an abstract function call.


答:
It help to understand exactly what Decorator Pattern allows you to do.

Let's just focus on a Decorator that wraps around a single function. (For all other method calls, the decorator would forward it right toward the underlying object.)

This is what the Decorator's method could possibly do:

Possibly do some of its own stuff before calling the underlying object

Possibly call the method of the same name on the underlying object

Or, possibly not. The call was eaten by my dog.

Or, still call it, but with a different set of parameters.

After returning from the method on the underlying object, possibly do some other stuff of its own.

Say, replace the returned value.

Or, throw a pizza.

By pizza I mean exception.

What Decorator could not possibly do, is:

A decorator method cannot dictate the internal control flow of the method in the underlying object, in ways that the underlying object doesn't expose.

What I mean by that is:

If the underlying object exposes toggles and switches which influence the internal control flow of its method, fine. Your decorator method can use these toggles and switches, and possibly restore them after returning from the underlying method.

If the underlying object doesn't allow you to influence some aspects of its internal control flow, you're stuck.

In this case, if you need to implement your own alternative control flow to completely replace the underlying method, there's a name for it. The Copy-and-paste Pattern.

However, you cannot do this:

Execute the next 253 bytes of machine code after entering the underlying method. Skip the next 47 bytes of machine code. Oh, by the way, inject some garbage into the underlying method's stack, and prepare to take over the machine's hypervisor with a zero-day exploit.

Actually you could possibly do that, but that's called a Trojan, not a Decorator.

So, going back to the main question. Should I use a Decorator, or a Derived Class?

I guess I'll leave that question to people who are infinitely more familiar with your code base.