问:
Deriving from a class only to provide a special constructor
In our codebase, I encountered the following construct: There is a base class B, and then there is a class D which derives from B, but does not override or add any members. In fact, D is completely empty - except for a constructor that initializes some (inherited) properties in a special way.

Consider this contrived C# example:

```<code>public class Angle
{
  public Angle(float degrees)
  {
    Degrees = degrees;
  }

  public float Degrees { get; set; }
}

public class RightAngle : Angle
{
  public RightAngle() : base(90)
  {
  }
}
</code>```

To me, this seems like a gross violation of OOP principles, but I cannot really pinpoint the issue. Is this a proper use of inheritance or a bad idea? Should I replace the derived class with -for example- a static factory?

答:
While mildly distasteful, this sort of thing isn't the worst thing in the world. It doesn't explictly violate any OO principles.

My main complaint is that with just the code above, not all right angles are RightAngles, though using value semantics would solve that.

Personally, I would work to make the class immutable and then simply have a static readonly instance of Angle.RightAngle or similar.


问:
How would I allow a PHP front end to communicate with a back end written in Go (or any other combination of languages)?
I like PHP. It's not overly complex to achieve what you want, you can write straight up HTML inside it, and I suppose I'm just used to it. I also like Go, having just discovered it while looking for something to write the back-end of a web app in that wasn't Node.js (can't abide callbacks everywhere).

I would like to be able to do most page generation in PHP because it's just what I'm comfortable doing for page generation, but I want the heavy lifting at the back to be done by Go. The back-end 'engine' needs to be able to do things like user-scheduled jobs to start with, but later extending to a web service endpoint and more, something I'd feel more comfortable doing in a compiled, statically typed language such as Go.

The only way I can think of allowing this to work is having all the PHP on an HTTP server and making REST or SOAP calls to the engine written in Go. Is this the only way to allow interoperability between the two languages or is there some other way?

答:
Sockets are a perfectly acceptable way to do language interop. The protocol you use to pass the messages between two different processes doesn't really matter much if you only plan to expose one of them to the rest of the world. If the long term plan is to make them both available then going with a standard protocol like HTTP with JSON is the right solution.

FFI (foreign function interface) is also a potential solution but I don't really know much about PHP and its FFI support to say whether this is better or worse than going with plain sockets.

ContentLicense: CC BY-SA 3.0


答: I believe the inheritance approach taken here in your question is to only guarantee that the object creation happens in a whole by appropriately setting the mandatory attributes of the class, if the proper object creation is the sole purpose then i would suggest object Builder patterns instead of going with the inheritance approach.</p>

Title: Deriving from a class only to provide a special constructor

Body:
In our codebase, I encountered the following construct: There is a base class B, and then there is a class D which derives from B, but does not override or add any members. In fact, D is completely empty - except for a constructor that initializes some (inherited) properties in a special way.

Consider this contrived C# example:

```<code>public class Angle
{
  public Angle(float degrees)
  {
    Degrees = degrees;
  }

  public float Degrees { get; set; }
}

public class RightAngle : Angle
{
  public RightAngle() : base(90)
  {
  }
}
</code>```

To me, this seems like a gross violation of OOP principles, but I cannot really pinpoint the issue. Is this a proper use of inheritance or a bad idea? Should I replace the derived class with -for example- a static factory?


问:
How to do "image shifting" faster?
I have a grayscale matrix (implemented as a simple array) to be shown on a display:

```<code>line 1: | a | b | c |
line 2: | d | e | f |
</code>```

a-f are grayscale values. This pattern has to be shifted by a variable percentage to the left or to the right.

What I currently do is an easy approach:

For example, shift 20% to left, so:

```<code>a_new = a * (1 - 0.2) + b * 0.2
b_new = b * (1 - 0.2) + c * 0.2
c_new = c * (1 - 0.2) + 0
</code>```

and so on. That is, I have a loop over all elements.

With only six elements I don't care, but in fact the matrix is much bigger.

Of course, the factor (1 - 0.2) can be reused, but I wonder if there is a smarter way of calculating the resulting (shifted) matrix?

答:
If your matrix can be accessed as a 2D array (x, y), then your problem generalises to

```<code>new(x, y) = old(x, y) * (1 - 0.2) + old(x + 1, y) * 0.2
</code>```

for all but the last column.  The last column is a special case.  Either use

```<code>new(x, y) = old(x, y) * (1 - 0.2)
</code>```

for that column only, or else pad your source array with an extra column of zeros first and then you don't have to treat the last column as a special case any more.

This can easily be implemented using two nested for loops.  Some specialised languages (such as Matlab) would be able to do the whole lot in one hit, with no explicit for loops at all.

Title: How to do "image shifting" faster?

Body:
If your matrix can be accessed as a 2D array (x, y), then your problem generalises to

new(x, y) = old(x, y) * (1 - 0.2) + old(x + 1, y) * 0.2

for all but the last column.  The last column is a special case.  Either use

new(x, y) = old(x, y) * (1 - 0.2)

for that column only, or else pad your source array with an extra column of zeros first and then you don't have to treat the last column as a special case any more.

This can easily be implemented using two nested for loops.  Some specialised languages (such as Matlab) would be able to do the whole lot in one hit, with no explicit for loops at all.


问:
What should the payload of a "domain event" generated through "change data capture" include?
Using domain driven design and event sourcing ...

Given I have a table of 3 columns: (A, B, C) with an existing row of data: (1, 2, 3), when I update the row to contain values (1000, 2, 3) and I run a tool designed to capture data changes and emit associated events, which of these should I expect as the emitted event's payload?

{date: 1234, newState: (1000, 2, 3)}

{date: 1234, prevState: (1, 2, 3), newState: (1000, 2, 3)}

{date: 1234, prevState: (1, 2, 3), newState: (1000, 2, 3)}, changed: (1,0,0)}

{date: 1234, newState: (1000, 2, 3), changed: (1,0,0)}

{date: 1234, changedData: (A: 1000)}

{date: 1234, changedData: (A: 1000), previousData: (A: 1)}

"Ideally" would like the design of the events to support wide variety of current and future uses including:

data replication

audit logging

event triggered activities

retroactive event insertion (possibly)

My thoughts:

Answer 1. above is the simplest, but clients that don't care about the "A" column still end up having to react to this event, as they can't tell from the event itself what's changed.

Answer 5. above is the cleanest - it just captures the "difference". The downside is that it forces the client to roll up changes to display an audit log of the full state on each change. Also event triggered activities may require knowledge of the full state to work.

Answer 4. above is perhaps more generally useful? It carries what's changed, but some contextual information alongside it.

Answer 2. above falls into a trap of asserting what the previous state was. What if that's not the previous state in your datastore, perhaps in a test environment? Do you reject the event as invalid? Would retroactively inserting an event mean changing all subsequent events "previousState" fields?

答:
You have two competing demands, and I think you need to choose which of them you want to win.
Demand 1, to have a fixed record of the state in each event. Useful for quick auditing by scanning the raw messages

Demand 2, to have a record of the changes applied in each event, to facilitate event sourcing.

Those two demands seem only subtly different, why not do both? Within that subtlety, however, you'll find that they are utterly conflicting. Demand 1 specifies that the knowledge of, and hence control of the mutation of state occurs with the sender, as it has absolute knowledge of the state (either before or after the change).  Demand 2 specifies that the knowledge of, and control of state mutation occurs in the receiver.

Demand 2 is suitable for event sourcing (recording that a change is requested), demand 2 is not, it is, as you say, more of an audit log (recording that a change has occurred)

So, for that reason, since you want to do event sourcing, the only possible workable format is 5.

Part of this is likely caused by the fact that you are coming at event sourcing by listening to mutation occurring in a database, whereas it should be the other way round, events causing the mutation to occur.

That's not to say that you can't get your scheme to work, and satisfy your requirements well, just don't think of it as event sourcing, as that's not what you actually want.

Adopting an event sourced data setup would support your needs above somewhat more easily, but adapting existing systems to that can be very involved to do.


问:
How to name a function type that is called by an event, but doesn't handle the event?
How would one name a function type called by a certain event? Instances of this function type would get called when a certain key is pressed. It isn't strictly an event handler type, because it doesn't have to handle the event. It might simply just want to be aware of the event. There can be multiple functions with this type listening for the same keystroke event.

I currently am using SpecificKeystrokeListener although that's not really correct as it doesn't listen, it is merely being notified.

For what it's worth, I am using Rust - though this applies to other languages as well. As an example:

type ResetFn = fn (this: *const device) -> ReturnStatus;

答: If the function listens for an event and then calls another function to handle it, I would call that function [Event]Dispatcher (replace [Event] with the name of the event. Think of the old time telephone dispatchers that you call into and ask to be connected to so and so. It seems like the perfect fit for what you're doing.</p>


问:
Algorithms: How do I sum O(n) and O(nlog(n)) together?
I have the follow algorithm which finds duplicates and removes them:

```<code>public static int numDuplicatesB(int[] arr) {
    Sort.mergesort(arr);
    int numDups = 0;
    for (int i = 1; i < arr.length; i++) {
        if (arr[i] == arr[i - 1]) {
            numDups++;
} }
    return numDups;
}
</code>```

I am trying to find the worst case time complexity of this. I know mergesort is nlog(n), and in my for loop I am iterating over the entire data set so that would count as n.
I am unsure what to do with these numbers though. Should I just sum them together? If I were to do that, how would I do it?

答:
Start with the definition of O ():

O (n log n) means "less than C n log n, if n is large".

O (n) means "less than D n, if n is large".

If you add both, the result is less than C n log n + D n < C n log n + D n log n < (C + D) n log n = O (n log n).

In general, if f (n) > C g (n) for large n and some C > 0, then O (f (n)) + O (g (n)) = O (f (n)). And after doing a few cases using the definition of O (), you'll know what you can and can't do.


问:
Migrating single-layer ORM based app to multi-layer API
I'm trying to understand what is the best way of migrating a website that works in a single layer and gets all the data via an ORM, to one that uses multiple layers, using an API backend to get the information needed to display a page.

In the project I'm working on, we have code like this, where data is retrieved via a Doctrine ORM:

```<code>$accountAddress = $sfUserProfile->getCustomer()->getAccount()->getAddress();
</code>```

Doing a naive translation of that to an set of API calls would result in 4 api calls. Although they may not be that slow individually, if we made one api call for each DB access that we currently have it would be incredibly slow.

That could be changed to a far more specific call like:

```<code>$backendAPI->getAddress($sfUserProfile);
</code>```

which would reduce those 4 API calls down to a single one, which is better. But it still leaves all the other queries that would need to be run for that page to be converted to separate API calls. I could write an api call that gets all of the user information required to display the user account information page in one go:

$info = $backendAPI->getInfoForAccountPage($sfUserProfile);
Where $info contains a set of simple entities (not ORM entities) e.g. :
$info = array(
   'customer' => $customer,
   'account' => $account,
   'accountAddress' => $accountAddress
);
(Or probably I'd create for each page a specific 'info' class to
enforce clarity on what info is available).

Is it 'correct' to write really specific API calls? Or what is the preferred method for avoiding having to have too many API calls to display a page?

The specific API call way seems sensible when there is a small known set of data that needs to be retrieved to display a page, but it seems like it might lead to having to write a lot of API end-points, so is there a better way of handling the problem?

答:
It sounds like your API is too granular; that is, you're retrieving chunks of data that are too small.

This code

```<code>$accountAddress = $sfUserProfile->getCustomer()->getAccount()->getAddress();
</code>```

would all run on the server, behind your service, so it's not four service calls, necessarily.  Rather than returning an account address from your service, you should return the entire customer object.

Body:
It sounds like your API is too granular; that is, you're retrieving chunks of data that are too small.

This code

$accountAddress = $sfUserProfile->getCustomer()->getAccount()->getAddress();

would all run on the server, behind your service, so it's not four service calls, necessarily.  Rather than returning an account address from your service, you should return the entire customer object.


问:
Erlang chat app design?
I have a chat app made in node/socket.io.

Scalability factors have made us choose Erlang/Ejabberd/xmpp and it will replace node/socket.

I have a few questions:

Currently using MySql for chat storage. Best alternative considering scaling and consistency as major factor?

Reason why I am switching : a row for single message is not the best thing to do, but since I am using MySql I am not left with any other option. Growing userbase doesn't help either.(Mnesia|Riak|MySql|PosgreSQL??)

How to send my chat messages from javascript to my Erlang code for storing/processing. I have done web development in past and ajax made my task very simple for client-server interaction. Node/socket event handler made my job easy while developing chat app. How will server and client interact in this scenario?

答:
Why not use something like Amazon s3 for your chat storage? I don't think you're going to find a higher scalability or availability outside of hosting your own cloud. Not sure how long your messages need to be stored either (Until the end of time?).

You're looking to have Erlang support REST services right? Here's a relevant SO question which namely calls out Mochiweb, Webmachine and Nitrogen. These will allow you to send and receive REST events to an erlang server. If you want to do AJAX over that, you could.

Title: Erlang chat app design?


问:
How to keep class parameters visible while using generic argument passing
After writing some classes where class initialization requires multiple options, instead of writing several parameters into constructors or setters, I started passing an associative array of parameters, which I called $options, where, for example:

```<code>$options = {'productLine' = $productLine, 'modelNumber' => $modelNumber, ... };
</code>```

My concern is that using such structure can lead to undesirable consequences.

Consider the following code, where by reading private variables, you pretty much know what this class needs to operate itself:

```<code>class Generator
{
    private $productLine;
    private $modelNumber;
    private $motorPresent;
    //... 5 similar lines

    function __construct($options)
    {
        $productLine = $options['productLine'];
        $modelNumber= $options['modelNumber'];
        $motorPresent= $options['motorPresent'];
        //... 5 similar lines
    }
}
</code>```

Now, consider this code, where by reading private variables, you do not really know what is being passed to it, other than some "parameters".

```<code>class Generator
{
    private $options;

    function __construct($options)
    {
        $this->options = $options;
    }
}
</code>```

It is not immediately clear what parameters are being passed from the source -- you have to know the actual $options array to know what is being passed.  To know what's going on you have to read the code, and that takes time.  Tests can be used to pass some sample parameters, but I wouldn't depend on tests as being the real answer.

My question is:

is there a way to keep assignments simple (like in my second code, code in constructor remains the same whether there are 10 parameters or 20), and yet still keep the class signature immediately apparent?

My current answer would be to either write code as in my first example, elaborating on which variable gets assigned what, but I feel that first way is needlessly verbose and I don't like it, because it introduces extra variable passing, when the variables are already in $options, just use $options['var_name'] instead.

Another way is to use comments, but that's not very good since comments are not always maintained as well as the code itself.

答:
One possible answer is to check that all operating conditions have been set correctly as such:</p>

```<code>function __construct($options)
{
    //check that everything is set properly
    if (!isset($options['productLine']))
        throw new \InvalidArgumentException("We need to know Product Line");
    if (!isset($options['modelNumber']))
        throw new \InvalidArgumentException("We need to know Model Number");
}
</code>```

Body:
One possible answer is to check that all operating conditions have been set correctly as such:

function __construct($options)
{
    //check that everything is set properly
    if (!isset($options['productLine']))
        throw new \InvalidArgumentException("We need to know Product Line");
    if (!isset($options['modelNumber']))
        throw new \InvalidArgumentException("We need to know Model Number");
}


问:
combining user data from user table and user_profile table to just one table
We are using two table to manage user data. A user table that has a username, email, password. Then a user profile that has first name, last name, bio, etc. Due to some other requirements it has been made clear it would be so much easier to combine the tables.

What is the thinking generally with separating these tables and what should I be concerned about if we combine them?

答:
As was noted in the comments, it sounds that under third normal form definitions, your proposed fusing of the tables is utterly correct.

Fuse 'em.


问:
Better way to train new hires
The team I currently am part of experiences fairly high turnover, with members typically moving to different projects within the same company.
Currently our "training" for new members is to pair them with a primary contact (usually the most recent person to complete their training) who will provide them with hands-on experience and will ask more senior developers if the newer hire ask something the mentor doesn't know. It provides a chance for the new hire to get involved quickly, and challenges the mentor to improve his/her understanding of the system also.

However, as you can imagine, this style of training is very time consuming, and doesn't provide a very good knowledge transfer (misconceptions propagate, gaps expand).

I've been tasked with generating documentation and training materials for our future new hires. I already do technical writing occasionally, but it's for the end user and is highly specific with lots of screenshots and consumes a large amount of time to complete.

Creating the new documentation for new hires is considered low priority and I've only currently got ~40 hours to work on it. Documenting the system the current way I write technical documentation would barely scratch the surface in 40 hours. Especially considering I have to document not only about the code base, but also about deployments and support.

How can I quickly write documentation to get new hires up to date as quickly as possible without investing significant time in writing the documentation?

Additional Information:

We currently have both a wiki, and some training documentation, however both are kind of sparse.

答:
I have recently started on a similar document at my place of work, with similar time constraints. I empathize that it is easy to want to write it at a very detailed level, as I did at first too, but that might actually be counter-productive.

If someone new is starting in a role, they are likely inundated with information for the first several weeks. Having their initial training be a brain dump of a developer who's been at a company for a number of years, will in my mind far over complicate what someone needs to know for their first few months or even year in that position. Keep it high level, try to use standard jargon and concepts, and then expand on them with the specifics from within the company's processes.

For me, the first iteration of this document is simply an outline of the SDLC that we use at my place of employment, with a list of roles associated within each step, a few examples of people who fulfill those roles, and specific checklists associated with each step of the lifecycle as well. I personally find checklists to be indispensable in training purposes, but also just about anything else I do at work. For example:

Project Manager (Joe) assigns you a task in Jira.

Set an estimated completion time on the task based on formula x.

Set the ticket as 'in progress' when you begin work on it.

Create branch from git, click link to view a 30 second video on this progress.

Write unit tests based on constraints in design document, see page y for unit testing naming conventions.

Set ticket for review and submit code to review system..' etc.

Your new employee should hopefully be familiar with the majority of the concepts, and now have a step by step guide of how the processes are applied at the company. I also do a quick demo of the process from start to finish using real documents from projects that I feel were well executed.

As mentioned, its also a living document, so sections can be expanded upon as it is identified that they need more information. The whole team should be involved in keeping it up to date. It can be a wiki, OneNote document, whatever, but something that all people can edit and review, then start to get other people involved in improving it when they've got a spare hour here and there. That way one person isn't doing it and propagating their own spin on the process to all the new hires.

Once they've reviewed the process, have them follow through on a small feature/bug fix on a non mission critical project and have them ask questions that the document doesn't cover. Record what these questions are, because they should probably be the first things you add to the document the next time you work on it.

Title: Better way to train new hires


答:
It's possible that the original design kept them separate because the original designer thought that the full user profile would not always be populated for each user. Their original goal might have been to separate a few mandatory fields from a large number of optional and sparsely used fields. They might have done this in an attempt to gain or improve performance of the system when querying the table.

It's also possible that there is (or was, at some point) a 1:n relationship between users and user profiles.

Title: combining user data from user table and user_profile table to just one table

Body:
We are using two table to manage user data. A user table that has a username, email, password. Then a user profile that has first name, last name, bio, etc. Due to some other requirements it has been made clear it would be so much easier to combine the tables.

What is the thinking generally with separating these tables and what should I be concerned about if we combine them?


问:
Does having many duplicated methods and deep inheritance hierarchies in GUI APIs (Java Swing, Android SDK) violate the SOLID design principles?
For those unfamiliar with the SOLID principles you can start reading here: Wikipedia article. However, most of my understanding comes from: http://www.objectmentor.com/resources/publishedArticles.html

Regardless, it seems that every GUI interface I run into in Java (even the one in Adobe Flex honestly) is filled with dozens of methods which are duplicated across many classes. Deep inheritance hierarchies are the norm and composition is definitely not preferred over inheritance. This seems to be a clear violation of SRP and ISP.

What I would like to know is, am I correct in thinking that these frameworks are violating the SOLID design principles? If so, then why?

Response to Snowman

I have to disagree that SWING is an example of SOLID. Lets use the JButton example:

1) SRP: The method isDoubleBuffered goes beyond the responsibility of JButton to represent a UI button. That method represents an implementation detail that has nothing to do with abstract concept of a UI button.

2) OCP: If I want to change how JButton handles events I have to replace the JButton class completely.

3) LSP: The implementation of JButton cannot be readily substituted with other implementations. JButton inherits most of it's implementation details directly. If I want to change the way a JButton creates tooltips, assigns action listeners, or access the graphics context, I have to throw away all of SWING. I cannot simply drop in a new class that handles those things since JButton inherits directly from JComponent.

4) ISP: The JButton public interface is littered with dozons of methods from every class that it inherits from. It is litterally a dumping group of public methods from JComponent, Container, Compound, etc. If the interface of JButton adhered to ISP there would only be 10 or so publically exposed methods.

5) DIP: JButton publicly exposes methods of it's concrete implementation details. If it applied true dependancy inversion then things like icon's, layout, event handling, etc would be delegated to separate classes that the user could readily switch out to achieve new functionality.

答:
In general, I disagree that GUI frameworks violate SOLID. There may be exceptions, but this wraps up my experience with multiple frameworks:

SRP: a GUI class typically has one responsibility. Maybe it is responding to an event, rendering an object, or maybe it is "represent this UI element." That last one might sound like it is not a "single" responsibility because that one responsibility is to tie everything together (e.g. JButton or JPanel). The key to look for is those "big" object often delegate to other objects that are specialized and handle one aspect of the object in detail (event handling, rendering, etc).

Open/Closed: Your example shows how UI classes are definitely open for extension: there is a lot of inheritance going on. One could argue that UI classes violate the "closed for modification" aspect since they are typically very configurable and can be modified to do a lot of things differently, but that is one purpose of these classes to begin with.

Liskov Substitution: in pretty much every framework I have seen, subclasses add more functionality and still allow parent class behavior. It does not always make sense, but it is supported. For example, you could nest UI elements inside of a button if it extends a frame (perhaps one could add an icon to a button this way, a picture element nested inside a button despite "button" not being commonly thought of as a parent element). This principle is key to the nested nature of UI frameworks.

Interface segregation: my main experience here is with Java, where there are many little interfaces for various listeners and handlers. Seems like a good fit.

Dependency inversion: along with the Liskov argument, many frameworks do rely on abstractions. For example, there may be some high level interface or abstract class to represent all UI components. Parent components can then accept any high-level component as a child, which allows arbitrarily complex layouts via nesting.

Overall, I think there is a strong argument for GUI frameworks adhering to SOLID.


问:
How can I team up two MVC frameworks without having them fight each other?
I'm creating a CRUD-based web project, and am thinking about using a server side MVC framework (such as CodeIgniter or Laravel) in tandem with a client side MVC framework (such as AngularJS). Is this a fairly common approach? After all, it's clear that I need something on the server, and that doing MVC on the client as well can enhance my application. But I feel that two MVC frameworks on the same project would just get in the way of each other and lead to disproportionate complexity and repetition.

What kind of approach or architecture would help me get the best out of both MVC frameworks when using one on the client, the other on the server?

答:
If you want to use AngularJS on the client side and Laravel on the backend is to first build a start page where your application loads and lives. And around that to build JSON-services (in laravel or some other, controller methods that handles responses and requests, your CRUD).

If you have a lot of different objects (tables?), make a start view for each one of them.

It's all different layers. The client-side MVC js-framework is optional, sure it can help a lot and structure an application, but you can have application structure without frameworks also. But it's up to you. If you feel compelled to those technologies, go ahead and start coding!


问:
Best way to organize SQL queries stored in your code ? (or should you?)
I am sure I am not the only one who gets frustrated when they see a page of code littered with SQL queries. The ActiveRecord and other ORM patterns help mitigate a good amount of SQL used in a project, but in many cases of complex queries, the use of SQL is seemingly unavoidable.

I am looking for opinions on how SQL queries should be organized with the rest of the code (or externally to it) to keep it from being scattered all over the place? One obvious idea is the use of Views, but often Views can be a source of performance issues when dealing with multiple large indexed tables, etc.

EDIT 1 - I am assuming you've already got it separated into the model layer

答: Generally, having a separate model layer is the best approach.  There are a number of enterprise design patterns that give ways to architect this.</p>

ContentLicense: CC BY-SA 2.5


问:
How to ensure multiple clients don't poll the server at the same time?
I am making an android app which will talk to a web service to get data. The web service has a rate limit of 100 calls per minute. Is there a way, recommended method to ensure that the app across various devices dont make the call to the server at the same time. Some way to stagger the requests across devices?</p>

答:
you need to implement a queue, not collision detection, when packets collide they are resend after the verifications, you have limited resources, if your detecting collision and resending data all the time, you can have a lot of problems with your hosting.

A time oriented queue, using time as metric you can control how much requests per minute you are handling without resending data.

Just saying.


问:
Would this be a proper use of threading?
After reading various MSDN articles, tutorials, and posts on here I came up with a design for a windows service that I wanted to make sure my threading strategy is proper and won't lead to memory, cpu, database issues.

Here is the basic flow.

MAIN THREAD

Collect list of service to be loaded.

Loads each service.

SERVICE THREAD (started by timer event on step 3)

Start Service

Setup Timer - Setup so there is no overlapping, only 1 processing call can be made.

Processing method

Makes database call to get information which is a list of Commands.

Gathers a collection of Handlers.

Does a Parallel.ForEach() over the list of Commands.

Immediately does a normal foreach() over the Handlers

COMMAND THREADS

Command does a normal foreach() over the Handlers passing in the Command.

Each Handler executes code that may CRUD the database or reach out to various other services.

Due to the Parallel.ForEach() I am spinning up 1 new thread per Command.

There could be 1000+

Since each Command has multiple Handlers these Handlers will run on the same thread as the Command.

This is to prevent database clashes since each Handler will be working with the same set of data.

This is to make each Command wait on its own Handler threads.

WAIT POINTS

Service waits for all Commands to finish executing before firing another round of round of commands.

Commands wait for all Handlers to to finish.

Handlers wait for one to finish before moving onto the next.

PERFORMANCE

3000x FOREACH Console.WriteLine() avg. 160ms

3000x FORALL Console.WriteLine() avg. 275ms

3000x FOREACH DatabaseCallAsync() avg. 1200ms

3000x FORALL DatabaseCallAsync() avg. 600ms

Interesting how the normal foreach was faster with just the WriteLine() but twice as slow with the database call. I still have concern about competing for resources with the other services.

QUESTIONS

Do you recognize any immediate issues with this design?

Do you have any suggestions that would make it more efficient with resources and speed?

I am noticing extremely high CPU usage on all cores when running just Console.WriteLines() in the actual execution point, should I be limiting the threads?

I noticed when I used a normal foreach() it still had pretty high cpu usage but had more resting points, I still need to put a counter in there to see how many calls are actually being made for each to see which is actually processing more but right now I am just concerned with the high usage.

答:
Your design looks solid, although, the slowest point of the entire operation is going to be the reads from the database. Consider using an Async call, as this will free up the processor to perform other actions as it awaits the return call from the database.

Your Parallel.ForEach is definitely the best option, while it does use the thread pool (as noted), it also separates the queue from the thread pool, and has essentially one queue per processor thus there is no waiting in a lock block as they ask for the next task. Then when they finish their queue, they go to the next one and ask it for some (incurring a small hit to performance, but much less than if they all used the same queue.)

The only question you may want to think about is: what does the main thread do as the supporting threads are running? If it is doing nothing, then it is just eating up processor time that could be spent elsewhere. Even if you have it (the main thread) sleep until the other threads are done, it comes alive every so often only to sleep again, and if you use something like a ManualResetEvent, which waits until the other thread has completed to continue, then it is needlessly taking up memory. Have it do something, even if it turns into a servicer thread.

In short, Parallel.ForEach = Good!

Use Async and Await for database calls

Don't create unneeded threads.

OwnerDisplayName: Tony


答:
In general, SOLID principles are usually met (See Snowman's answer)

But since you mentioned the Android SDK, I will go a little into detail on how SOLID principles coming too short in this particular API.

Single responsibility principle. The View class is responsible for

positioning

drawing

event processing

handling a huge load of other callbacks.

So, if you consider the SRP as "A class should only have one reason to change" - you already lost the argument. They tried it by creating ViewGroup and making the ListView use an Adapter for the actual data. These things actually work quite well.

Open closed principle. Although basically open for extension, unfortunately only via inheritance. There's no way no modify behavior (e.g something in the drawing or layouting process) via strategy-pattern or something similar. Everything is a constant, so you have to choose between the existing options.

Liskov substitution principle is of course met via the java language requirements. I do remember though, that we had issues with TextView or EditText in the past, were the inherited method returned the same type and was named the same; behaved differently anyway. The post-condition wasn't met. Too bad I don't remember exactly what it was. Something with the Focus or same properties having different result or something.

Interface segregation. What should I say? The basic View interface is polluted with methods over methods. Why is the scrolling implemented (and accessed) via the View class? Remember the callbacks I mentioned before? But in general, if you're trying to "implement" the View "interface" (extending the class) you only need override the methods you really need - but this is more like a language feature in java. If you see it more pedantically, you'll actually implement scrolling by overriding the class even if you don't need it.

Dependency inversion seems to be ok in android. But I'm sure that if you really search for it, you'll find enough spots in the framework were something depends on an implementation instead of an abstraction. I'm not sure whether the 34 instanceof calls in the View class are a sign of good abstractions.

In general, the android sdk tries its best fulfilling all principles. I also know that it's fairly large and also needs to take performance into account, so it's harder to make it fulfill all principles.

I should add, that I probably wouldnt be able to do any better.

Title: Does having many duplicated methods and deep inheritance hierarchies in GUI APIs (Java Swing, Android SDK) violate the SOLID design principles?

Body:
For those unfamiliar with the SOLID principles you can start reading here: Wikipedia article. However, most of my understanding comes from: http://www.objectmentor.com/resources/publishedArticles.html

Regardless, it seems that every GUI interface I run into in Java (even the one in Adobe Flex honestly) is filled with dozens of methods which are duplicated across many classes. Deep inheritance hierarchies are the norm and composition is definitely not preferred over inheritance. This seems to be a clear violation of SRP and ISP.

What I would like to know is, am I correct in thinking that these frameworks are violating the SOLID design principles? If so, then why?

Response to Snowman

I have to disagree that SWING is an example of SOLID. Lets use the JButton example:

1) SRP: The method isDoubleBuffered goes beyond the responsibility of JButton to represent a UI button. That method represents an implementation detail that has nothing to do with abstract concept of a UI button.

2) OCP: If I want to change how JButton handles events I have to replace the JButton class completely.

3) LSP: The implementation of JButton cannot be readily substituted with other implementations. JButton inherits most of it's implementation details directly. If I want to change the way a JButton creates tooltips, assigns action listeners, or access the graphics context, I have to throw away all of SWING. I cannot simply drop in a new class that handles those things since JButton inherits directly from JComponent.

4) ISP: The JButton public interface is littered with dozons of methods from every class that it inherits from. It is litterally a dumping group of public methods from JComponent, Container, Compound, etc. If the interface of JButton adhered to ISP there would only be 10 or so publically exposed methods.

5) DIP: JButton publicly exposes methods of it's concrete implementation details. If it applied true dependancy inversion then things like icon's, layout, event handling, etc would be delegated to separate classes that the user could readily switch out to achieve new functionality.


问:
Domain Model, validation, and pushing errors to the model
Looking into DDD and something I noticed is that business logic should be in the model, otherwise you just have property bags.  That said how do you handle pieces of validation that require a trip to the database?

For example, you have an domain object that represent categories for a blogging engine.

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}
```

<p>From a developer's perspective, you could create an empty category, but this isn't valid in the business world.  A <code>Category</code> <strong>requires</strong> a Name to be a valid category, therefore we end up with:</p>

<pre class="lang-cs prettyprint-override"><code>public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Category(string name)
    {
        Name = name;
    }
}
</code>```

Now, a Category can't be created without a name.  But, we can't have duplicate Category names either, that would just cause confusing and redundancy.  I don't want the entity to handle it themselves because this would end up more of an Active Record Pattern and I don't want the model to be "self-aware/persisting" so to speak.

So to this point, where should this validation take place.  It is important that if the user types an duplicate Category, we would notify the user of this.  Should there be a "service" layer that takes a UI model and turns it into the domain model and attempts to validate it, pushing errors back to the UI, or should there be something closer to the data layer that handles this?

Someone please set me straight because I really like where DDD is going, I just can't make all the connections to get there myself.

答:
I would create a domain service responsible for validating the uniqueness of the category. In my solution domain defines the interface of the service, infrastructural part implements it using a database.

Please also take a look at https://stackoverflow.com/questions/516615/validation-in-a-domain-driven-design.


问:
Which one of these would be the better way to implement object copying in c#?
I would like to be able to copy an object and only change a few values. I have come up with two different ways to do this.

```<code>// OPTION A - create a copy constructor and use property
//            initialization to change values

class SomeObject {
    public string PropertyA { get;set; }
    public string PropertyB { get;set; }

    public SomeObject() { }

    public SomeObject(SomeObject copyFrom) {
        PropertyA = copyFrom.PropertyA;
        PropertyB = copyFrom.PropertyB;
    }
}

var original = new SomeObject() {
    PropertyA = "original value",
    PropertyB = "some other original value",
}
// replace only the values I want to replace
var partialCopy = new SomeObject(original) {
    PropertyA = "some new value different from original",
};

// OPTION B - create an Option<T> type and use that

// used as constructor paramaters
public class Option<T> {

    // used in the case where you want
    // the default value of a type instead
    // of the original value (see usage below)
    public static readonly Default = new Option<T>(default(T));

    public T Value { get; private set; }

    public Option(T value) {
        Value = value;
    }

    public static implicit operator T(Option<T> o) {
        return o.Value;
    }

    public static implicit operator Option<T>(T value) {
        return new Option<T>(value);
    }
}

public class SomeObject {
    public string PropertyA { get; set; }
    public string PropertyB { get; set; }

    public SomeObject() { }

    public SomeObject(SomeObject toCopy,
        Option<string> propertyA = null,
        Option<string> propertyB = null)
    {
        PropertyA = propertyA ?? toCopy.PropertyA;
        PropertyB = propertyB ?? toCopy.PropertyB;
    }
}

var original = new SomeObject() {
    PropertyA = "original value",
    PropertyB = "some other original value",
};
// replace only the values I want to replace
var partialCopy = new SomeObject(original,
    propertyA: "new value");
</code>```

The first implementation has much less code to maintain, but you can't enforce things in the constructor. The second is a bit more complicated due to the Option<T> class but you can, in effect, enforce rules better in a constructor at object creation. Do you think the constructor safety of OPTION B overrides the complexity, making it the better choice. Or should I use the simpler OPTION A due to ease of maintenance?

These are simple data transfer objects. They generally have a lot of properties. I'm trying to avoid creating objects like template, templateB, templateB.2, etc. when I can just copy the current object and change the properties I need. For example, properties A,B, and C need to be set to this value when a particular rule passes. However further in the process, properties D,E, and F will need different values based on other rules. I'm trying to avoid code like the following:

```<code>  // I'm trying to avoid this
  ResponseObject SomeMethod(bool inputA, bool inputB) {
     var myObject = CreateObjectFromTemplateA(); // has same values for A,B,C
     if(inputA) {
         myObject.D = "some value";
         myObject.E = "some value";
         myObject.F = "some value";
     } else if (inputB) {
         myObject.D = "some other value";
         myObject.E = "some other value";
         myObject.F = "some other value";
     }
     return myObject;
  }

  // and do something like this instead
  ResponseObject SomeMethod(bool inputA, bool inputB) {
      var defaultValue = CreateFromTemplateA()
      return inputA ? new ResponseObject(defaultValue) { D = "some value",
                                                         E = "some value",
                                                         F = "some value",},
           : inputB ? new ResponseObject(defaultValue) { D = "some other value",
                                                         E = "some other value",
                                                         F = "some other value",},
                    : defaultValue;
  }

  // in some cases it's as simple as one property change
  // and here is where the first method of property initialization
  // breaks down
  ResponseObject SomeMethod(bool inputA, bool inputB) {
      return new ResponseObject(CreateFromTemplateA()) {
             D = inputA ? "some value"
               : inputB ? "some other value
                        : CreateFromTemplateA(), // a second object created
      };
  }

  // here is where the constructor initialization helps
  ResponseObject SomeMethod(bool inputA, bool inputB) {
      return new ResponseObject(CreateFromTemplateA(), // with this method CreateFromTemplateA() could be a property instead of a method call
          d: inputA ? "someValue"
           : inputB ? "someValue"
                    : null // null here indicates use the property value from CreateFromTemplateA()
      );
  }
</code>```

答:
I would do it via fluid Interface / method-chaining:

```<code>class Person {

  [...]

  public Person WithFirstName( String FirstName ){
    this.FirstName=FirstName;
  }

  public Person WithLastName( String LastName ){
    this.LastName=LastName;
  }

  [...]

  public Person Clone(){

    Person clone = new Person()
                        .WithFirstName(this.FirstName)
                        .WithLastName(this.LastName)
                        [...]
    return clone;
  }

}
</code>```

So if you need an object with different values, you would do it with:

```<code>Person personB=personA.Clone()
                      .WithFirstName("John");
</code>```

This makes your intention clear:

1) You send a message to a person-Object: clone yourself

2) You send a new message to the clone, that you wish it with a different first name.

Body:
I would do it via fluid Interface / method-chaining:

class Person {

  [...]

  public Person WithFirstName( String FirstName ){
    this.FirstName=FirstName;
  }

  public Person WithLastName( String LastName ){
    this.LastName=LastName;
  }

  [...]

  public Person Clone(){

    Person clone = new Person()
                        .WithFirstName(this.FirstName)
                        .WithLastName(this.LastName)
                        [...]
    return clone;
  }

}

So if you need an object with different values, you would do it with:

Person personB=personA.Clone()
                      .WithFirstName("John");

This makes your intention clear:

1) You send a message to a person-Object: clone yourself

2) You send a new message to the clone, that you wish it with a different first name.


问:
Why would I use ElasticSearch if I already use a graph database?
I don't find any deep explanation on the web about a comparison between ElasticSearch and the graph databases.

Both are optimized to traverse data.

ElasticSearch seems to be optimized for analytics.

However Neo4j is also based on Lucene to manage indexes and some fulltext features.

Why would I use ElasticSearch if I already use a graph database ?

In my case, I'm using Neo4j to build a social network.

What real benefit may ElasticSearch bring?

UPDATE ----------

I've just found this paragraph:

There are myriad cases in which elasticsearch is useful. Some use
cases more clearly call for it than others. Listed below are some
tasks which for which elasticsearch is particularly well suited.

Searching a large number of product descriptions for the best match
for a specific phrase (say “chef’s knife”) and returning the best
results

Given the previous example, breaking down the various
departments where “chef’s knife” appears (see Faceting later in this
book)

Searching text for words that sound like “season”

Auto-completing a search box based on partially typed words based on
previously issued searches while accounting for mis-spellings

Storing
a large quantity of semi-structured (JSON) data in a distributed
fashion, with a specified level of redundancy across a cluster of
machines

It should be noted, however, that while elasticsearch is
great at solving the aforementioned problems, it’s not the best choice
for others. It’s especially bad at solving problems for which
relational databases are optimized. Problems such as those listed
below.

Calculating how many items are left in the inventory

Figuring out the
sum of all line-items on all the invoices sent out in a given month

Executing two operations transactionally with rollback support

Creating records that are guaranteed to be unique across multiple
given terms, for instance a phone number and extension

Elasticsearch
is generally fantastic at providing approximate answers from data,
such as scoring the results by quality. While elasticsearch can
perform exact matching and statistical calculations, its primary task
of search is an inherently approximate task.

Finding approximate
answers is a property that separates elasticsearch from more
traditional databases. That being said, traditional relational
databases excel at precision and data integrity, for which
elasticsearch and Lucene have few provisions.

Can I assert that if I don't need approximate answers, then ElasticSearch would be useless compared to an already used graph database?

答:
I hesitate to call ElasticSearch a database. It is not a replacement for a database, but it makes a good addition to add functionality, specifically advanced text searching, along side your existing database.

I see where you can get them confused. They can actually fit the same need, but not always. ElasticSearch does exactly what it sounds like, searches. A graph database doesn't specify relations or indexes, where as ElasticSearch does. So fundamentally they work quite differently. ElasticSearch analyzes documents with, for example, English analyzer. What this does it will take words and analyze different variations of that word or even synonyms. For example, dig, would be anaylzed as dig,digs,dug,digging,digger .... When you run a query on elasticsearch your queries can also be analyzed, then those words are queried for and can be scored by relevance.

ElasticSearch is a great tool, because it's really flexible. You can find a wide range of relative content, or you can find a needle in the hay stack, and its relatively easy.

Graph Databases have their advantage too. Finding relevance/relations between things like hash tags for example, or things with many mutable relations. They're great and interesting pieces of technology, however I'd have to say that its not as powerful as ElasticSearch. Mostly because ElasticSearch is geared towards this sort of thing, and it handles analysis for you so you can do full-text search. However if you're looking to use a system more so like twitter's search that's based on predefined tagging/keywords, then you'd be better off using the Graph Database your already using.

The question is how robust do you want your searching to be? If you have a need to do really fine grain(full text) searches I'd use elasticsearch. Otherwise you can always implement a search relatively easily on a graph database. Once you have search implemented its not impossible to migrate to elasticsearch if you find yourself later needing a more robust search engine, just implement your search with that in mind.


问:
Should we call Web API from MVC application in same solution?
I am working on a project in MVC that has mobile application so one thing is clear that we have to use Web API so it can used in mobile application.

After creating API when we started to develop Web site we are confused and had discussion on whether to use API or directly access to the Business object. And we ended up after having opinion form more experienced developer to consume Web API instead of using Business object directly.

I'm having confusion regarding to this solution structure.

1) Why we should use Web API and make HTTP request (which is time consuming) to get or put data  instead of business object directly which is in same solution.

2) After having arguments they said what if client wants to host API and web on different cloud server and apply scaling only on API or may be he want to have different url for accessing API and Web (which is some what logical). So in that case should we call Web API from MVC application in same solution?

3) If we're hosting API and Web on different hosting so it means our Web will use WebClient and have HTTP call on each navigation. Is it right?

4) If we'll business object form both API and Web hosting on different server then if something change in BL will need to update build on both server.

5) Or we should create only one project for API and can add views or html pages to develop Web interface so in that way we can directly call API from ajax.

As per my knowledge #5 is the best solution or API is only for 3rd party access. If we have DB, EF, data layer and business layer in same solution then we should not use API to make HTTP calls and directly access business object.
(correct me if I'm wrong)API is needed when mobile application or desktop or any one want to access application so we can have same repository and data layer.

In my scenario I've to create API as we also have mobile application, and in project API side we called business layer (separate project) and business layer communicate to data access layer (separate project). So my question is if we host our API and web to different servers then calling API which is a HTTP request may take longer rather than using method from business layer as we create the project and we've .dll of business layer. In API controller we just convert out put of our business to json format.

I've searched on internet but didn't get convincing  answer. I've found a blog http://odetocode.com/blogs/scott/archive/2013/07/01/on-the-coexistence-of-asp-net-mvc-and-webapi.aspx discussing same point but again in that blog my question is why we need to consider scenario #3?

Update:
We can have different API project and MVC project and we can call API from web using jvascript or can use MVVM pattern.

答:
Great question!  I'm always looking for a better way to structure my projects..  Each point you raise has merit and having explored a variety of solution structures I have to say that I agree the majority of the comments here: there is no perfect solution.  A few things to ask yourself when faced with this kind of problem: How complex is this application?  With how many systems will I need to integrate -- or how many systems will need to integrate with this system?  How much testing do I plan on doing?  Is there a separate design/UI team?  Will we need to scale?  What constitutes a session?

Let's look at a couple of scenarios and ways to use a little clever engineering to make things really bang (and some tricks to make things a bit easier)..

Hosting Both API and Website in the Same Project

In this case, you may have a single solution with zero or more business layer projects and a single hybrid MVC/WebAPI project (as well as other projects - utility, etc).

Pro's

Everything is in one place..  No need to shoe-horn in complicated messaging (HttpClient calls), you can have shared session state (client and server via cookies, InProc/OutOfProc session, etc), connection pooling, shared logic, etc.  Deployment could not be more simple.

Con's

Everything is in one place..  This is probably the most monolithic structure possible.  There are no clearly defined interfaces between your layers.. You end up with high-cohesion.  Lazy developers will avoid interfaces when dealing with this type of architecture which makes testing a huge pain.  Scaling/co-locating the application will be difficult.

Uses

I would use this project structure for a one-off, internal, or simple application.  Building a quick system for tracking basketball camp sign-up at the local Y?  This is your architecture!

WebAPI and Website in Different Projects

I tend to prefer this case.. You have a single solution with one (or more) MVC project(s) and one WebAPI project.

Pro's

Modularization!  Loose Coupling! Each project can stand alone, be tested separately, and can be managed differently.  This allows you to more easily implement different caching strategies depending on your needs.  By keeping solid boundaries between your different systems, you can more easily establish contracts which allow you to enforce specific usage patterns and cut-down on possible friction (read: fewer bugs with less opportunity to abuse the API).  Scaling is a bit easier as you only need to scale the bits that are seeing high load.  Integration becomes a bit easier to handle as well because you will need to have an idea about what your API is going to look like from the start.

Con's

Maintenance is a bit more difficult.  Multiple projects means you will need project/feature owners to keep track of merges, contracts (interfaces), deployments, etc.  Code upkeep, technical debt, error tracking, state management -- all become concerns as they might need to be implemented differently based upon your needs.  These kinds of applications also require the most planning and curating as they grow.

Uses

Building an application that could have 100 users today and 100,000 next week/month?  Does the application have to send notifications, manage complex workflows, and have multiple interfaces (web + mobile app + SharePoint)?  Have lots of time on your hands and love solving 5000+ piece puzzles over the weekend?  This is the architecture for you!

Tips

Having outlined the above, I can understand how your next project might look a bit daunting.  No worries, here are a few tricks I've learned over the years..

Try to use stateless sessions.  On smaller systems, this might mean storing an encrypted cookie containing at least the current user's internal id and a timeout.  Larger systems might mean storing an encrypted cookie with a simple session id which might be fetched from a datastore (redis, table storage, DHT, etc)..  If you can store enough information so that you don't have to hit the main database on every request then you will be in a good place - but try to keep cookies under 1k.

Be aware that there will probably be more than one model.  Try to think in terms of models and projections (the links I found here were.. not good.. think: one man's inventory item is another man's order line item - same basic underlying structure, but different views).  Some projects have a different model for each logical/conceptual boundary (i.e. using a specific model for communcation with a specific API.

API's Everywhere!  Anytime an object/class/structure exposes any data or behavior, you are establishing an API.  Be mindful of how other entities or dependencies will be using this API.  Think about how you might test this API.  Consider what might be talking to this API (other objects via code?  Other systems via a protocol?) and how that data is exposed (strongly typed? JSON? * cough * XML?).

Build for what you have, not what you imagine that you will have two years from now.  Another answer references YAGNI - they're absolutely correct!  Solving imaginary problems makes your deadline imaginary.  Set solid goals for your iterations and meet them.  Deploy!  A project in development is a project with only one user - you!

YMMV (Your Mileage May Vary).  There is only one absolute here: there is a problem, you are building a solution.  Everything else is completely up in the air.  Both solutions above can be made a wild success -- and a sucking failure.  It is all up to you, your tools, and how you use them.  Tread lightly, fellow developer!


问:
Static and not-static: programmer quantum theory
Let me illustrate using the PHP language. The discussion here is, how should I do exactly to solve this problem in a clear and unambiguous mode.

Imagine that I have a class called Path. This class is responsible for defining an object that refers to a path of a file, for example. This class helps me with some tasks, for example:

```<code>$pathInstance = new Path("path/to/file.bin");
$pathInstance->exists();             // Return if file exists.
$pathInstance->get_dirname();        // Return the dirname of file.
$pathInstance->get_basename();       // Return the basename of file.
$pathInstance->is_file();            // So on...
</code>```

However, there is a problem in this methodology when I need to, at the same time, use a static method that allows to perform a task without creating an instance. For instance:

When I call is_file() it'll check if the internal path if $this is refer to a file. But I want to do it too statically, for instance, Path::is_file("path/to/file.bin").

In PHP this is not recommended, and is required to make a basic workaround. And I personally think is not the right concept to be applied.

Imagine that I have it:

```<code>class Path {
    /** @var string */
    private $path;

    /** @param string $path */
    function __construct($path) {
        $this->path = $path;
    }

    /**
     * Normalize the path.
     * @param  boolean $force_normalize Force even if path doesn't exists.
     * @return string|false
     */
    public function normalize($force_normalize = null) {
        if($force_normalize === true) { /* ... */ }
        return realpath($this->path);
    }
}
</code>```

So I use as:

```<code>$pathInstance = new Path("/abc/../def");
echo $pathInstance->normalize(); // output "/def"
</code>```

But I would like to work TOO statically, for instance:

```<code>echo Path::normalize("/abc/../def"); // output "/def"
</code>```

答:
To me, this is a question of class design.

If we are designing for target implementation languages such as C++, Java, and the like (if you will allow them to be lumped together), the questions are

what use cases do you want to support?

how should their interfaces be structured?

how can those two masters be best supported and balanced?

You have given a requirement for the first question - you want static (class) methods and dynamic (instance) methods. For a given method, for now lets call these two methods classMethod and instanceMethod. We'll give them better names later.

For the second question, the interfaces to the two methods must be different. At present they have different names, but we would like them to be the same if they do the same job. What are the options?

We could put them in different classes, but that would just make our design more complex.

We could give them the same name, and then they'd need different parameter lists.

The second one is ideal for this problem. We can call our methods myMethod() for the instance method version, and myMethod(path) for the class version.

Regarding implementation, we could make our instance method call the class method, passing it's path. Or make the class method construct an instance and then call the instance method. Since I can see reasonable implementation alternatives, my high level class design job is done.

So as an implementer, my concerns will be

which approach is more natural in my target language?

do I want my implementation to match other implementations in other languages?

will there be obvious performance losses in choosing one implementation over another? (I say losses here, because while I wish to avoid premature optimization, I also want to avoid "deliberately inefficient" implementations).

Finally, given intuition that one implementation will not have a great advantage over the other, I would implement myMethod() to call myMethod(path).

Hope that helps.


问:
Exception class for each exception or for all framework
I am developing a framework and it can generate various types of exceptions. Initially I'm working with a single exception class that indicates that something went wrong inside the framework. However, I was thinking, maybe it would not be correct to create a specific class for each specific type of exception?

Currently:

There is an unique exception class, which can generate messages like:

Framework_Exception: file not found;

Framework_Exception: method not found;

Framework_Exception: programmer not found;

A possible method more correct

In this case, there should be an exception class for each specific type of error. All of them would inherit the main class (or the class that grouped this type of exception).

Framework_FileNotFound_Exception extends Framework_Exception;

Framework_MethodNotFound_Exception extends Framework_Exception;

Framework_ProgrammerNotFound_Exception extends Framework_Exception;

Framework_Method_Exception extends Framework_Exception;

Framework_Method_InvalidCall_Exception extends Framework_Method_Exception;

Framework_Method_IncorrectParam_Exception extends Framework_Method_Exception;

Which conceptually would be better accepted?

答:
Using separate exception types for the different types of error that all inherit from a single exception base class is the more useful option for users of your framework.

Using separate exception types has the advantage that users of your framework have the option to implement error handling that is specific for that type of error.

For example, an application could implement a strategy to look for files in multiple different locations based on the Framework_FileNotFound_Exception. And they could instruct the user to call a particular phone number in response to the Framework_ProgrammerNotFound_Exception.

Such different handling is not really possible when all exceptions have the same type.

Inheriting from a common exception type gives your users the additional option to choose to ignore the differences between the error types.


问:
How does the CPU access the values of stack-allocated variables?
Consider the following C++ function:

```<code>void doStuff() {
    Thing thingA;
    Thing thingB;
    thingA.doSomething();
    // .. etc
}
</code>```

During the execution of this function, variables thingA and thingB are allocated on the stack. That means that the variable thingA represents some address on the stack, and it's value is what's allocated in this address (correct me if I'm wrong).

What I don't understand is this: when we call thingA.doSomething(), how does the CPU know what the address represented by thingA is? The value held by thingA is currently buried in the stack under some other data. How does the CPU know what the address that leads to this value is, in order to reach this data?

答:
The first thing to note is that to the CPU, the stack is just a portion of the total memory that gets used in a particular way. Addresses of objects on the stack are indistinguishable from addresses of other objects (globals and heap allocated objects).

When invoking a method or a function, the compiler knows where the object and parameters are located and tells the compiler where to look for them. This can be a memory address or a CPU register.

Due to the way that the stack is typically used, objects on the stack usually don't have a fixed address. But they do have a fixed address relative to the other stack-allocated objects in the same function and that knowledge is used to determine where they are exactly located.

In most CPU architectures, two registers are used to keep track of the top of the stack and the location relative to which the stack-allocated objects in the current function invocation are located. These registers are sometimes referred to as respectively the stack pointer and the base pointer.


答:
The compiler will choose a different offset from the stack pointer for each stack-allocated variable. For example, stackPointer + 0 bytes might point to thingA, and stackPointer + 8 bytes might point to thingB.

The compiler will make sure that the offsets are large enough that the memory used for each variable doesn't overlap. On each function call, the stack pointer is moved to make space for the callee's variables. On function return, the stack pointer is reset back to where it was in the caller, so that variable references in the caller still work correctly.

Title: How does the CPU access the values of stack-allocated variables?

Body:
Consider the following C++ function:

```<code>void doStuff() {
    Thing thingA;
    Thing thingB;
    thingA.doSomething();
    // .. etc
}
</code>```

During the execution of this function, variables thingA and thingB are allocated on the stack. That means that the variable thingA represents some address on the stack, and it's value is what's allocated in this address (correct me if I'm wrong).

What I don't understand is this: when we call thingA.doSomething(), how does the CPU know what the address represented by thingA is? The value held by thingA is currently buried in the stack under some other data. How does the CPU know what the address that leads to this value is, in order to reach this data?


问:
IoC as service locator
I have been wondering for quite some time on some issues while using dependency injection:

In a layered application, I normally inject repositories into the application service using constructor injection:

```<code>public class SomeService
{
    private IRepositoryA _repoA;
    private IRepositoryB _repoB;
    private IRepositoryC _repoC;

    public SomeService(IRepositoryA repositoryA,
                       IRepositoryB repositoryB,
                       IRepositoryC repositoryC
                       /* Other dependencies*/)
    {
        _repoA = repositoryA;
        _repoB = repositoryB;
        _repoC = repositoryC;
    }

    public void SomeMethod1()
    {
        //Do something with repo A and B
    }

    public void SomeMethod2()
    {
        //Do something with repo C
    }

    //Other methods
}
</code>```

The problems with this are:

When the service becomes complicated, the number of dependencies will grow more and more, and soon the constructor will become ugly with lots of parameters. It might be the service is doing too many things (violate SRP) and better be separated into several classes, but I think this situation is not uncommon so I'm curious how others solve this

SomeMethod1() only uses repo A and B, but when client calls it, the service is created with all repositories, meaning it has more dependencies than it needs.

To address those 2 issues, I see some people have another abstraction, which is repository factory

```<code>public interface IRepositoryFactory
{
    T GetRepository<T>() where T : IRepository;
}

public class RepositoryFactory
{
    public T GetRepository<T>()
    {
        //Use IoC to return correct IRepository
    }
}
</code>```

and inject factory into service class:

```<code>public class SomeService
{
    private IRepositoryFactory _factory;
    public SomeService(IRepositoryFactory factory)
    {
        _factory = factory;
    }

    public void SomeMethod1()
    {
        IRepositoryA repoA = _factory.GetRepository<IRepositoryA>();
        IRepositoryB repoB = _factory.GetRepository<IRepositoryB>();
        //Use repo A and B
    }

    public void SomeMethod2()
    {
        IRepositoryC repoC = _factory.GetRepository<IRepositoryC>();
        //Use repo C
    }

    //Other methods
}
</code>```

This does solve the 2 problems above, but there are a few other issues:

RepositoryFactory is using IoC as a service locator, which is considered as anti-pattern by many people

RepositoryFactory has a dependency on IoC framework now, which might be undesirable in dependency injection (because as I understand, the application should have as little understanding about the IoC as they can, except for composition root, which is at the top of the application)

So is this a good approach to use?

答:
Good Question!

When the service becomes complicated, the number of dependencies will grow more and more

In that case your dependencies are maybe not standalone dependencies but can be grouped into simple dependency-holding classes that can be used to pass into the constructor.

A good sign would be if more than one of your classes use both IRepositoryA an IRepositoryB in the constructor and also in some of their methods like in your SomeMethod1 method.
You should be able to find a good name for the class that groups IRepositoryA and IRepositoryB. If not, consider going to tell us the real example so we can analyse better.

SomeMethod1() only uses repo A and B, but when client calls it, the service is created with all repositories, meaning it has more dependencies than it needs.

But that is okay because normally you want to make sure that at the time when the class is created you don't want the IRepositories to be changed anymore. They should be declared as immutable. That is a good practice.

If that's not the case and they shall be mutable, then you could make the IRepositoryC dependency beeing passed into SomeMethod2 as parameter. Currying / partial applying can help you to prevent code-duplication here when you call the method many times with the same IRepositoryC argument.

A different approach would be passing option-types into the constructor. Your class would then however have the responsibility to check in their methods if a given IRepository has already been provided or is still empty at the time of the method call.

So it depends a little on what you really want to do. There is imho no general answer to this problem.

Title: IoC as service locator


问:
Should I declare the most specific type as return type of method?
In Android I can put only ArrayList of Parcelable objects in Intent:

```<code>Intent putParcelableArrayListExtra(String name, ArrayList<? extends Parcelable> value);
</code>```

I can't put in there a List<? extends Parcelable>.

I have private method that get list of Parcelable objects from Intent (i.e. the method is used in its own class).

As I said there is always ArrayList in Intent. Should I declare return type of this method as ArrayList<>?   Or List<>?

I think that ArrayList would be better because an ArrayList is also a List. But I often read that I should declare field type as most general possible type. I.e., Collection<> (or List<> if I need ordered collection) instead of ArrayList<>. But I don't see any reason to do so for this method return type.

答:
A declaration (whether a return type, an API comment or a contract) is a promise that you will deliver some good or perform some service. Declaring a specific return type is a greater promise than declaring a general type that is good enough for the caller, because it ties you down do a more specific action.

If that is really what you are doing and always will be what you are doing, then there's no problem with that. But if one day you want to refactor, extend or improve your program in a way that involves a new, better container type, you won't be able to, because client code would break if you switch to CoolNewList structures. Then you will say to yourself, "Gee, I wish I had listened to those wise people at StackExchange and made minimal promises instead of boasting with concrete types!", but it will be too late for you. Then you will start advising younger coders to keep their promises minimal, and so the cycle of life continues.


答:
To me, SQL is a fundamental part (in a lot of cases, the majority) of the business logic code.  If you try to separate it from the code that operates on the returned data, you are more prone to unbalance the understandability and maintainability of the code.

As I look at it, reading data, processing data, writing data, searching data... they are all similar operations, and best kept in the same place.

If you start to sense a duplication of efforts with queries, then perhaps you need a database view or an object that can encapsulate that aspect of database access.

Another tip is to actually have a good database query method.  In software I write (PostgreSQL, MySQL, SQL Server), I have ensured that the bulk of my query operations can take place as a single statement of code.

```<code>GetValue(SQL, [transaction], [array_of_params])
GetRow(SQL, [transaction], [array_of_params])
GetRowList(SQL, [transaction], [array_of_params])
GetValueList(SQL, [transaction], [array_of_params])
Execute(SQL, [transaction], [array_of_params])
</code>```

Those are (roughly) the main function calls that I ensure are part of my "connection object".  It depends on the language, what you actually implemente, but my point is to keep it really, really simple and painless.

In summary, treat SQL as a native part of programming, and do not abstract for the sake of abstraction.

Title: Best way to organize SQL queries stored in your code ? (or should you?)

Body:
I am sure I am not the only one who gets frustrated when they see a page of code littered with SQL queries. The ActiveRecord and other ORM patterns help mitigate a good amount of SQL used in a project, but in many cases of complex queries, the use of SQL is seemingly unavoidable.

I am looking for opinions on how SQL queries should be organized with the rest of the code (or externally to it) to keep it from being scattered all over the place? One obvious idea is the use of Views, but often Views can be a source of performance issues when dealing with multiple large indexed tables, etc.

EDIT 1 - I am assuming you've already got it separated into the model layer

Body:
To me, SQL is a fundamental part (in a lot of cases, the majority) of the business logic code.  If you try to separate it from the code that operates on the returned data, you are more prone to unbalance the understandability and maintainability of the code.

As I look at it, reading data, processing data, writing data, searching data... they are all similar operations, and best kept in the same place.

If you start to sense a duplication of efforts with queries, then perhaps you need a database view or an object that can encapsulate that aspect of database access.

Another tip is to actually have a good database query method.  In software I write (PostgreSQL, MySQL, SQL Server), I have ensured that the bulk of my query operations can take place as a single statement of code.

GetValue(SQL, [transaction], [array_of_params])
GetRow(SQL, [transaction], [array_of_params])
GetRowList(SQL, [transaction], [array_of_params])
GetValueList(SQL, [transaction], [array_of_params])
Execute(SQL, [transaction], [array_of_params])

Those are (roughly) the main function calls that I ensure are part of my "connection object".  It depends on the language, what you actually implemente, but my point is to keep it really, really simple and painless.

In summary, treat SQL as a native part of programming, and do not abstract for the sake of abstraction.


问:
How would I allow a PHP front end to communicate with a back end written in Go (or any other combination of languages)?
I like PHP. It's not overly complex to achieve what you want, you can write straight up HTML inside it, and I suppose I'm just used to it. I also like Go, having just discovered it while looking for something to write the back-end of a web app in that wasn't Node.js (can't abide callbacks everywhere).

I would like to be able to do most page generation in PHP because it's just what I'm comfortable doing for page generation, but I want the heavy lifting at the back to be done by Go. The back-end 'engine' needs to be able to do things like user-scheduled jobs to start with, but later extending to a web service endpoint and more, something I'd feel more comfortable doing in a compiled, statically typed language such as Go.

The only way I can think of allowing this to work is having all the PHP on an HTTP server and making REST or SOAP calls to the engine written in Go. Is this the only way to allow interoperability between the two languages or is there some other way?

答:
PHP is a server-side programming language. If you want to communicate with other applications, you need to implement webservices in your Go and have PHP doing requests to those webservices. There are various ways already implemented in most of the established frameworks (Laravel, Phalcon, Symfony, Zend, CodeIgniter, CakePHP and so on - the list really is huge). The way to achieve this without a PHP framework behind your project, is via cURL calls.

However, the workflow of this is as follows: the user will have to initiate an action by doing a request to your PHP server-side component, which in turn will do a cURL request to the Go backend and afterwards serve the appropriate response back to the user. It's basically the same thing as the user doing a request directly to the Go backend, except you can do intermediary processing in the PHP component, on your requests to and responses from the Go backend.


问:
When does one hard-code actual data values into the code as opposed to using a DB?
A long-standing question for me has been: when do I store data (actual values) in a database table, and when do I store them right in the code?

The untold consensus has typically been as such(*):

If it is a single variable or a simple structure, or an array of a few values, put data right in the code.

[* consensus has been debated in comments and answers, but basically I wanted some kind of a premise to jump-start the question, so feel free to challenge and improve upon it]

Example:

```<code>$number = 44;
$colors = array("blue", "yellow", ... "mauve");
</code>```

If it has hundreds+ of rows of data of the same type, use a database.

But there seems to be a gray area; what about cases that are not so clear? What considerations and factors does one need to pay attention to in order to make a decision?

Example:

Say your company uses 10-15 different types of motors frames that can be represented as "412T". You have about 30 of them and they change rarely.  You can either create a DB table for those or hard-code them in a database.  In this case, motors are static, physical things that are not likely to change often.

Keeping them in code subjects them to source control, where in a database, DB changes are typically not tracked.  But keeping them in a database frees up (separates) code from data.

Another (actual) example I can use is this question of mine: https://stackoverflow.com/questions/26169751/how-to-best-get-the-data-out-of-a-lookup-table (currently 48 rows of option data).

答:
It is neither the frequency of changes nor the amount of data that decides where to store data.

If the data is required to run the program, it is part of the program code, so store it as a constant. All other data goes in the database.

Of course, config files, images, sounds, etc are usually better stored on the filesystem.


答: If there's even the slightest chance you will ever get a phone call resulting in you having to rebuild an application because something hard-coded has changed, then don't hard-code it. At the very least keep it in a config file or db table. You don't have to provide any UI to maintain it necessarily, but dialling in and changing a config file or running an SQL UPDATE on a table is surely preferable to rebuilding the whole shooting match.</p>

Title: When does one hard-code actual data values into the code as opposed to using a DB?

Body:
A long-standing question for me has been: when do I store data (actual values) in a database table, and when do I store them right in the code?

The untold consensus has typically been as such(*):

If it is a single variable or a simple structure, or an array of a few values, put data right in the code.

[* consensus has been debated in comments and answers, but basically I wanted some kind of a premise to jump-start the question, so feel free to challenge and improve upon it]

Example:

```<code>$number = 44;
$colors = array("blue", "yellow", ... "mauve");
</code>```

If it has hundreds+ of rows of data of the same type, use a database.

But there seems to be a gray area; what about cases that are not so clear? What considerations and factors does one need to pay attention to in order to make a decision?

Example:

Say your company uses 10-15 different types of motors frames that can be represented as "412T". You have about 30 of them and they change rarely.  You can either create a DB table for those or hard-code them in a database.  In this case, motors are static, physical things that are not likely to change often.

Keeping them in code subjects them to source control, where in a database, DB changes are typically not tracked.  But keeping them in a database frees up (separates) code from data.

Another (actual) example I can use is this question of mine: https://stackoverflow.com/questions/26169751/how-to-best-get-the-data-out-of-a-lookup-table (currently 48 rows of option data).


答:
The distinction is indeed a somewhat gray area, but my approach to this kinds of issues is: does the data change in production"? Anything that changes after deployment in a production environment should go in the database, even for things that may rarely change.

So the question you should be asking is not "how often will it change?", but "can it change?". If a value for a property can vary within the same code iteration (without touching anything else in the code) on the production environment, it goes into the database.


答:
The main problem with your second approach of injecting factories is that it removes one of the benefits IoC/dependency injection provides - You no longer know which repositories the class depends upon without digging through the code.

While this is not as 'bad' as creating the repositories itself, the class still needs to know how to request them from a factory.  Also, you've added extra complexity by introducing the factory itself.

You are probably be better off following your instinct that the class is doing to much and separating it out into smaller chunks of responsibility.

I completely agree with the answer provided by @valenterry it's like most things, ymmv and it really depends on what you want to do.  The second approach isn't exactly evil and is perfectly servicable if that's what you end up with.

Title: IoC as service locator

Body:
I have been wondering for quite some time on some issues while using dependency injection:

In a layered application, I normally inject repositories into the application service using constructor injection:

```<code>public class SomeService
{
    private IRepositoryA _repoA;
    private IRepositoryB _repoB;
    private IRepositoryC _repoC;

    public SomeService(IRepositoryA repositoryA,
                       IRepositoryB repositoryB,
                       IRepositoryC repositoryC
                       /* Other dependencies*/)
    {
        _repoA = repositoryA;
        _repoB = repositoryB;
        _repoC = repositoryC;
    }

    public void SomeMethod1()
    {
        //Do something with repo A and B
    }

    public void SomeMethod2()
    {
        //Do something with repo C
    }

    //Other methods
}
</code>```

The problems with this are:

When the service becomes complicated, the number of dependencies will grow more and more, and soon the constructor will become ugly with lots of parameters. It might be the service is doing too many things (violate SRP) and better be separated into several classes, but I think this situation is not uncommon so I'm curious how others solve this

SomeMethod1() only uses repo A and B, but when client calls it, the service is created with all repositories, meaning it has more dependencies than it needs.

To address those 2 issues, I see some people have another abstraction, which is repository factory

```<code>public interface IRepositoryFactory
{
    T GetRepository<T>() where T : IRepository;
}

public class RepositoryFactory
{
    public T GetRepository<T>()
    {
        //Use IoC to return correct IRepository
    }
}
</code>```

and inject factory into service class:

```<code>public class SomeService
{
    private IRepositoryFactory _factory;
    public SomeService(IRepositoryFactory factory)
    {
        _factory = factory;
    }

    public void SomeMethod1()
    {
        IRepositoryA repoA = _factory.GetRepository<IRepositoryA>();
        IRepositoryB repoB = _factory.GetRepository<IRepositoryB>();
        //Use repo A and B
    }

    public void SomeMethod2()
    {
        IRepositoryC repoC = _factory.GetRepository<IRepositoryC>();
        //Use repo C
    }

    //Other methods
}
</code>```

This does solve the 2 problems above, but there are a few other issues:

RepositoryFactory is using IoC as a service locator, which is considered as anti-pattern by many people

RepositoryFactory has a dependency on IoC framework now, which might be undesirable in dependency injection (because as I understand, the application should have as little understanding about the IoC as they can, except for composition root, which is at the top of the application)

So is this a good approach to use?


问:
OOD: Java inheritance and access to child methods via casting
I have several classes Parent and Child1 ... Child9 implemented in Java. Parent is an abstract class, containing all the common variables of the child classes (a lot, which is the main reason why I made Parent an abstract class and not an interface), some abstract and some implemented methods.

Some of the child classes have custom methods which are specific to them. So often I find myself calling a child method using downcasting:

```<code>Parent p = new Child1();
((Child1) p).child1SpecificMethod();
</code>```

Somehow I have the feeling that this is bad OOD practice, but I am not quite sure if that really is the case respectively how to improve the design.

- Edit -
What I probably should change anyway is the fact that I use the Parent class for organizing many (for now) common variables, making them (or a container object) members of the concrete classes.

答:
Your feeling is right to consider it a bad practise. Imagine your example code a little different:

```<code>Parent p = createObject();
((Child1) p).child1SpecificMethod();
</code>```

How do you know, that the value of p is really Child1? You don't and this can cause a ClassCastException at runtime. If you need to call child1SpecificMethod() in your code you have to make sure that p is of type Child1. If that is not possible because Object p is passed to your code (e.g. as a method parameter) as type Parent, you could consider using a variant of the Visitor-Pattern and execute child1SpecificMethod in the handle-Method of your visitor object, that handles Child1.

Body:
Your feeling is right to consider it a bad practise. Imagine your example code a little different:

Parent p = createObject();
((Child1) p).child1SpecificMethod();

How do you know, that the value of p is really Child1? You don't and this can cause a ClassCastException at runtime. If you need to call child1SpecificMethod() in your code you have to make sure that p is of type Child1. If that is not possible because Object p is passed to your code (e.g. as a method parameter) as type Parent, you could consider using a variant of the Visitor-Pattern and execute child1SpecificMethod in the handle-Method of your visitor object, that handles Child1.


问:
How can IO cause side effects in Functional Programming?
Whenever I read about Haskell, I find that IO can cause side effects.

But I do not understand how it would do it?

Do we mean that we are writing to a file from one lazy sequence and another lazy sequence is reading from same file?

Is that the only possibility or is there something fundamentally deep?

答: Simplest possible example: printing "Hello, world!" changes the state of the system, because the console now displays "Hello, world!", and earlier it didn't. Not only have you changed the state, it's actually impossible to change it back, since you can't un-get characters from a terminal! That's about the most serious side effect possible.</p>


答:
Use lookup of capabilities instead.
Give no access to the child classes, consider them implementations of the Parent class.

Then define interfaces specifying some capability, feature.

```<code>interface Child1Specific {
    void child1SpecificMethod();
}
</code>```

Usage:

```<code>Parent parent = ...
Child1Specific specific = parent.lookup(Child1Specific.class);
if (specific1 != null) {
    specific1.child1SpecificMethod();
}
</code>```

This discovery mechanism is very flexible. Using delegation instead of inheritance can be quite rewarding. Note, having child classes is no longer needed.

Or in java 8 (where several variations are possible, and the interface could be functional too):

```<code>Optional<Child1Specific> specific = parent.lookup(Child1Specific.class);
if (specific1.isPresent()) {
    specific1.get().child1SpecificMethod();
}
</code>```

Make in the Parent class a lookup for some capability:

```<code>public class Parent {
    protected final Map<Class<?>, Object> capabilities = new HashMap<>();
    protected final <T> void registerCapability(Class<T> klass, T object);

    public <T> T lookup(Class<T> klass) {
        Object object = capabilities.get(klass);
        return object == null ? null : klass.cast(object);
    }
</code>```

Or in java 8:

```<code>    public <T> Optional<T> lookup(Class<T> klass) {
        Object object = capabilities.get(klass);
        return Optional.ofNullable(klass.cast(object));
    }
</code>```

The child class:

```<code>class Child1 extend Parent implements Child1Specific {
    Child1() {
        registerCapability(Child1Specific.class, this);
    }
}
</code>```

Or more dynamic:

```<code>class Child1 extends Parent {
    private Child1Specific specific = new Child1Specific() {
        ... Parent.this ...
    };
    Child1() {
        registerCapability(Child1Specific.class, specific);
    }
}
</code>```

Title: OOD: Java inheritance and access to child methods via casting

Body:
I have several classes Parent and Child1 ... Child9 implemented in Java. Parent is an abstract class, containing all the common variables of the child classes (a lot, which is the main reason why I made Parent an abstract class and not an interface), some abstract and some implemented methods.

Some of the child classes have custom methods which are specific to them. So often I find myself calling a child method using downcasting:

```<code>Parent p = new Child1();
((Child1) p).child1SpecificMethod();
</code>```

Somehow I have the feeling that this is bad OOD practice, but I am not quite sure if that really is the case respectively how to improve the design.

- Edit -
What I probably should change anyway is the fact that I use the Parent class for organizing many (for now) common variables, making them (or a container object) members of the concrete classes.

Body:
Use lookup of capabilities instead.
Give no access to the child classes, consider them implementations of the Parent class.

Then define interfaces specifying some capability, feature.

interface Child1Specific {
    void child1SpecificMethod();
}

Usage:

Parent parent = ...
Child1Specific specific = parent.lookup(Child1Specific.class);
if (specific1 != null) {
    specific1.child1SpecificMethod();
}

This discovery mechanism is very flexible. Using delegation instead of inheritance can be quite rewarding. Note, having child classes is no longer needed.

Or in java 8 (where several variations are possible, and the interface could be functional too):

Optional<Child1Specific> specific = parent.lookup(Child1Specific.class);
if (specific1.isPresent()) {
    specific1.get().child1SpecificMethod();
}

Make in the Parent class a lookup for some capability:

public class Parent {
    protected final Map<Class<?>, Object> capabilities = new HashMap<>();
    protected final <T> void registerCapability(Class<T> klass, T object);

    public <T> T lookup(Class<T> klass) {
        Object object = capabilities.get(klass);
        return object == null ? null : klass.cast(object);
    }

Or in java 8:

    public <T> Optional<T> lookup(Class<T> klass) {
        Object object = capabilities.get(klass);
        return Optional.ofNullable(klass.cast(object));
    }

The child class:

class Child1 extend Parent implements Child1Specific {
    Child1() {
        registerCapability(Child1Specific.class, this);
    }
}

Or more dynamic:

class Child1 extends Parent {
    private Child1Specific specific = new Child1Specific() {
        ... Parent.this ...
    };
    Child1() {
        registerCapability(Child1Specific.class, specific);
    }
}