答:
Yes, some times it is very convenient to be able to locally modify a pass-by-value argument to a function. For example, the argument might be a reference to a node of a linked list, and within the function you may want to traverse the list, so you will want to be doing node = *(node.next);.

So, ill-advised? definitely not, in my opinion.

There exist languages which do not allow you to modify function arguments, (Pascal, I think?) which forces you to make a copy of the argument into a local variable in order to modify it, and then the problem is that both the copy and the original argument are in scope, so further down in your code you may mistakenly read the argument instead of the variable.  This kind of mistake is arguably more likely than an inadvertent modification of the argument. So, by allowing the argument to change, you eliminate the variable, and therefore the possibility of such a mistake.  (I will not even bother with the performance issue, it is negligible, and even optimizable by the compiler.)

As for the possibility of mistakenly modifying thing, this is what I have to say:

In my experience, about 90% of the member variables, parameters, and local variables that we declare are effectively const.  (final in java, readonly in C#.)  This means that although we do not explicitly declare them as const, we treat them as const: we never change their value after initialization.  Therefore, I hope a language (*1) will be created one day in which all "variables" will be const unless explicitly declared to not be const with the use of a special "non-const" (mutable perhaps?) keyword.  This way, in the rare event that a variable is expected to change, it will be immediately obvious in its declaration, and the compiler will even be able to issue a warning if you declare something as mutable and yet forget to change it.  This will, of course, also have the benefit of preventing you from unintentionally modifying your thing if you have not declared it as mutable.

(*1): an imperative language, since one might point out that functional languages already do that.


问:
How to measure the potential value of refactoring
On an old,  large project with technical debt how can you reliably estimate or measure the benefit of refactoring code?

For example, say you have some components within a software stack solution written in an older language, and some later components written in a newer language. New features and bug fixes are constantly being added to this solution by a development team.

The developers suggest that replacing the existing old language components with the new version would be 'a good thing' However, no extra features would be added by this work and it will cost x dev-days.

A sales person suggests adding 'a great new feature'. the company measures the value of his suggestion by using a formula. ie. It will earn the company F million pounds, over t years at a cost of x dev-days work

How can the company cost up the refactoring proposal in a meaningful way? and under what circumstances is it likely to be the most profitable option for the company?

答:
I think the point the other answers miss is you need to measure the cost of refactoring against the lost revenue from not refactoring.

Refactoring for the sake of changing code is a waste of time. It needs to bring value to the table. In this context I do not mean spending an hour refactoring a problem class, but the major refactoring such as changing to a different CLR language as you used in your example.

If we keep doing what we are doing, are we missing out on something? Is there a crufty old design in place that is holding us back from realizing value? For example, if we want to add a feature is it so difficult that it might take e.g. 100 hours to implement, vs. 50 hours to refactor and 25 hours to implement against the new design?

Does the existing code carry technical debt that is costing us money? Is this crappy old code the source of bugs? Do we end up working for free to fix problems because of it? Nobody likes giving away lucrative billable hours for free.

Is the cost of refactoring equal to or less than the cost of not refactoring?

Is it possible to amortize the cost by having a small team of rockstars refactor the code causing the most problems? Can we spread the refactor out across releases? There are small inefficiencies everywhere: can we "fill in the gaps" so to speak with this extra work?

ContentLicense: CC BY-SA 3.0


问:
Refactoring long methods with a lot of cyclomatic complexity
I'm attempting to refactor what is becoming a very large method -- currently 350 or so lines -- that contains a high degree of cyclomatic complexity.

I understand and ascribe to the theories that methods should be short and that concerns should be separated, and I've been reading over things like this and this among others.  I'm struggling to refactor my method, though, for a couple of reasons.  To help illustrate these, first here is a simplified example of what the method looks like before refactoring:

```<code>private static void ProcessMessage(Message toProcess)
{
    var processingIssues = new StringBuilder();
    var transformedAttachments = new List<TransformedAttachmentData>();

    foreach (var attach in toProcess.Attachments)
    {
        //in reality there is quite a bit of nested logic here,
        //but I'll represent it as a single if-else block.
        if (true)
        {
            //in reality, a third-party library is used in multiple
            //levels of this logic hierarchy to produce the transformed data.
            transformedAttachments.Add(new TransformedAttachmentData(attach));
        }
        else
        {
            processingIssues.AppendLine(
                string.Format(@"Issue ""{0}"" occurred with " +
                @"attachment ""{1}"".", "blah blah problem", attach.Name));
        }
    }

    /*
     * do something else complex here with
     * processingIssues and validResults
     */
}
</code>```

First, the very cyclomatic complexity which is concerning to me is born of a complicated set of business rules that need to be applied which together sum up to a couple shared sets of data (represented here as processingIssues and transformedAttachments).  Basically what this means to me is that not only should I break the foreach out into its own method, but I should also further consider breaking the logic tree contained within it into additional methods in the interest of keeping my methods "short".  In other words, it would seem as though it's not enough just to break my current method into its two obvious outer-most parts: "pre-processing" and "post-processing" of the attachments, if you will.  How far do I need to go with this given that I am dealing with a complicated logic tree with concerns that are not so "separate" from one another.  In other words, if "separation of concerns" is one reason to refactor to smaller methods, but so is "cyclomatic complexity" -- both of which seem to be orthogonal concepts -- which is the "right" reason to refactor, and how should I do it in the latter case?

Second, in order to separate out some of the concerns to separate methods, those separate methods will have to return multiple variables (again, processingIssues and transformedAttachments), both of which are only needed within the separate methods themselves, so I'm faced with the choice: use output parameters, or create a small class to wrap the return values.  Which is better?

Any guidance on this topic and my specific hang-ups would be much appreciated.

答:
Your scenario seems like you have placed an entire "message processing subsystem" inside a single function.  In order to simplify the function, you will need to come up with an actual message processing subsystem consisting of several classes.  Some, if not all, of these classes will need to be instantiated, allowed to run, and discarded on each invocation of your method.

This will be a subsystem which will have some state and some classes implementing operators (the actual rules.)  The issue of returning multiple results is transformed into the task of modifying more than one item of state of the subsystem, and the issue of various rules interacting with each other is also transformed into having some rules modifying the state of the subsystem while other rules look at this modified state in order to figure out what to do.

Essentially, there would be a pretty close correlation between the set of local variables of your function and the set of member variables of the message processing subsystem class, though the subsystem might need to contain more member variables in order to capture information which is currently encoded in conditional branching (if statements) in your existing method.

Needless to say, the total number of lines in such a subsystem might easily exceed your current 350 lines by a factor of 2 or 3, so, before you embark on such a refactoring, consider whether you really need it.


问:
How do I convince my users not to use a sketch UI?
I recently worked on a prototype of a new system using Sketchflow, and now some key stakeholders are pushing for a sketched look & feel in the final product. To make matters worse, the people viewing the prototype were asked to provide feedback on the sketched look & feel by way of a fairly leading survey question, to which 80% of the responses were positive.

It's for an enterprise application that will mostly be for internal clients, but is also intended to be used by some external clients.

The main reasons I have for it thinking it's a bad idea are:

It doesn't look polished or professional

The significant effort involved in skinning an actual application in the sketched style

The sketched style doesn't make efficient use of screen real-estate

I've been trying to figure out what the appeal could possibly be, and the only thing I can come up with is that people are attracted to the simplicity of it -- especially when compared with the existing system(s) it will be replacing.

Can anyone point me in the direction of evidence of why using a sketch look & feel is a bad idea? Ideally something based on UI research. I'm worried that my voice isn't going to be listened to unless I can point to something concrete.

[Edit]

I should probably add that the difficulty of skinning the application is compounded by the fact that it is intended to be delivered as one or more Silverlight webparts in a Sharepoint site. Getting a consistent sketched look & feel across both technologies could be very difficult.

[Edit]

Just in case anyone's not sure about what a Sketchflow prototype looks like (and therefore what the people in question are asking for) they're essentially asking for a production application to have a pencil-sketch wireframe look & feel.

答:
Usually, such sketched prototypes look good as long as no-one has to use it. To convince them, implement a small part as a usable prototype, in two version, one with the sketched skin and one normal. That should be enough to show them that the sketched look is funny for one day or two, but becomes stale soon after.

If this doesn't convince them, well, their problem.

ContentLicense: CC BY-SA 2.5


问:
Complex data structure in python: just dict, etc, or some classes?
Consider a web service API that returns a complex Json object. Using the stock Python tools for the job, this will read in from the web service as a dict which contains, in turn, a mixture of arrays, dicts, strings, and numbers.

I confess: this data is born in Java. In Java, there's a data model for this data. My question is, would dyed-in-the-wool Python programmers desire a Python class data model that adds some notational niceness, or would they expect to just be handed the situation described in the first paragraph.

In code terms, what's the value of:

```<code> text.tokens[3].part_of_speech
</code>```

as opposed to:

```<code> text['tokens'][3]['part_of_speech']
</code>```

?

Based on some comments, I want to expand this a little. What I wrote above is all about consuming a complex data structure that arrives in Python as Json, and I can see that 'sugaring' it with a pile of classes with @property markers is not very helpful.

Another side of the coin is assembling one of these. As, admittedly, a person who has spent a lot more time in Java, C++, C (and Lisp?) than in Python, I would tend to see value in some API that helps me remember the names of all the bits and pieces. So maybe that suggests simply providing constants that provide the defined keys?

答:
I don't know that there is one answer that everyone would agree with, but personally I would just use the built in Python classes. Reading JSON to python dictionaries and lists is a very standard thing to do, it maps very well.

I'm all and for OO programming, but I don't see the point in writing a tiny class to be a thin wrapper over existing powerful data types. When someone reads your code, it's just one more type to grok. Whereas standard data structures are, well, standard. They know it's a dict, if a programmer wants to understand the contents at some point, they can just place a breakpoint, print it out, and let the program keep running.

In addition, python has a lot of really nice syntax like dict and list comprehensions. You're probably losing as much niceness as you gain by not having to type a few extra []'s.

Representing JSON in C++ or Java is a different situation, because if the JSON structure is not known at compile time, so the types are not known in advance. So writing a custom data structure is pretty well necessary anyway. Very different in python.


问:
Should a comparison method ever return the same type back as it's comparing?
First, this is homework, but no, I'm not asking for anyone to do any code for me. My course start date isn't for another month (it's online), so I can't ask for clarification. I thought I'd see if this method description even makes any sense in the eyes of the community.

I had to create a class AddressBook that contains contact information such as someone's first, middle, and last names, their phones numbers... etc. (The class should really be called AddressBookEntry to make sense).

After creating the class, step 2 was to create a static method with the signature:

```<code>public static String compareNames(String name1, String name2)
</code>```

And the only description of what they want is:

Using the get and set methods, create a comparison method
  compareNames(name1, name2) that compares the first, middle, and last
  names of strings name1 and name2. Assume that name1 and name2 follow
  the following format: “FirstName M. LastName”.

To me, this doesn't make any sense. I've never seen a comparison method return anything other than a boolean or an signed int for inequality comparisons. The only thing I could think of was returning something like the first chunk of the second name that matches the first; but that seems rather arbitrary.

Maybe I'm missing something here though. How should I interpret this question?

The course has a general discussion board that I can read but not (yet) post to. Someone posted the exact same question as me, and someone else replied with a message from the tutor:

It will return a string that contain the result of comparison between name1 and name2.

Turns out it's not a typo; but that "clarification" didn't really help.

答:
The specification is rather vague, but "comparison method" generally means comparing the two arguments, so the result could be "they're equal or not" (as in Object.equals), which means the result type should be bool, or it could be "first is less, equal, or greater than the other", in which case the result type is either int (as in IComparable.compare), or an enum (as Haskell uses).

It's very unlikely that the result type of comparing two values is of the same type, unless the type being compared is already a bool or int.


问:
PHP Multi-Page / Session Question
I created index.php that basically looks up all the individual php files (articles) in a few subfolders and prints them out.  Since the quantity of articles is over 30 and growing, I implemented a multi-page solution using PHP session().  So, page2.php simply prints out the second part of my array titled "page2" and page3.php prints out the third part of my array titled "page3".  These array parts are arrays themselves (it's an array of arrays).

All works fine.

However, this requires me to hard code "page2.php", "page3.php", etc.  This will get out of hand at some point.

How would you guys handle this?  Can I dynamically create "pageX.php" upon user clicking the "Next" button?  Or, should I do some type of AJAX solution?  Is there a standard way of doing a multipage PHP index?

答:
It is much more common to use url parameters.  For example:

```<code>example.com/index.php?page=1
example.com/index.php?page=2
</code>```

Then on index.php you can use $_GET['page'] to figure out which page you are retrieving, then serve that data.  If you are actually generating php files on your server you can serve that page using:

```<code>include 'page2.php';
</code>```

Or even better:

```<code>include 'page'.$_GET['page'].'.php';
</code>```

Disclaimer: You should sanitize your variable before using it: such as:

```<code>$page = sanitize($_GET['page']); //You need to write the sanitize function
include "page$page.php";
</code>```

Title: PHP Multi-Page / Session Question

Body:
It is much more common to use url parameters.  For example:

example.com/index.php?page=1
example.com/index.php?page=2

Then on index.php you can use $_GET['page'] to figure out which page you are retrieving, then serve that data.  If you are actually generating php files on your server you can serve that page using:

include 'page2.php';

Or even better:

include 'page'.$_GET['page'].'.php';

Disclaimer: You should sanitize your variable before using it: such as:

$page = sanitize($_GET['page']); //You need to write the sanitize function
include "page$page.php";


问:
Functional programming and Text adventures
This is mostly a theoretical question about FP, but I'll take text adventures (like old-school Zork) to illustrate my point. I'd like to know your opinions on how would you model a stateful simulation with FP.

Text adventures really seem to call for OOP. For example, all the "rooms" are instances of a Room class, you can have a basic Item class and interfaces like Item<Pickable> for things you can carry and so on.

World modeling in FP works differently, especially if you want to enforce immutability in a world that must mutate as the game progresses (objects are moved, enemies are defeated, the scoring grows, the player changes its location). I imagine a single big object World that has it all: what are the rooms you can explore, how they are linked, what the player is carrying, what levers have been triggered.

I think that a pure approach would be to basically pass this big object to any function and have it returned by them (possibly modified). For example, i have a moveToRoom function that gets World and returns it with World.player.location changed to the new room, World.rooms[new_room].visited = True and so on.

Even if this is the more "correct" way, it seems to be enforcing pureness for the sake of it. Depending on the programming language, passing this potentially very big World object back and forth may be expensive. Also, every function may need to have access to any World object. For example, a room may be accessible or not depending on a lever triggered in another room because it may be flooded, but if the player carries a life jacket, it can enter it anyway. A monster may be aggressive or not depending on whether the player has slayered his cousin in another room . This means that the roomCanBeEntered function needs to access World.player.invetory and World.rooms, describeMonster needs to access World.monsters and so on (basically, you must pass the whole load around). This really seems to me to call for a global variable, even if this is all but good programming style especially in FP.

How would you solve this problem?

答:
Myself, I would definitely look into the ability of the language in question to access some form of database. Most of the events that happen to change the state of the world concurrently would simply be recorded to disk, and would not affect the current player within the current room (outside of special circumstances such as explosions, or in an MMO, switches that open doors remotely, other players' shouts, etc).

As such, the current client really only needs to be aware of the Room object, and things that affect it directly. noticableEventsOutsideRoom could then simply be a subclass of Room affected by recent changes to the database, and your game object has become much smaller.


问:
Algorithm to find whether there is a path (any path) above length X between two vertices
We all know how to find the shortest path between two vertices, but what if I just want to know the answer to this question - is there a path, (any path), between vertex A and B of length larger than some X?

Should start from the shortest path, and then merge adjacent nodes if its length is less than X? (or extend the search "circle" gradually)

I don't want to first find all possible paths and then filter out those shorter than X, I want to stop the moment I find any path above a certain length between the two vertices, (and stop if I haven't found one after some MAX iterations)

(I assume I first do a shortest paths to find if there is at all any path between the nodes to avoid searching if there isn't)

It somehow feels it should be simpler that what I'm making it, but I can't seem to find a text-book algorithm for it (e.g. BFS / DFS / Dijsktra / Bellman Ford are not really helping here, right?)

I'm sure it's simple, but I need some push in the right direction.

答: The problem you describe is the decision version of the longest path problem (ie. "Is there a path of length at least k?"). As Jimmy Hoffa noted, the problem is NP-complete. You could look into approximation algorithms for the LPP, particularly ones that exploit any special structure your graphs might have.</p>


问:
Share some fields but others unique to owner of instance
I've been programming for many years and this is sort of a strange need and I've never seen anything like this but I have a game where there are abilities that you can do. There is an ability class that stores data like Name, DamageType, DamageValue, Cooldown, CurrentCooldown. It's a very generic class where the instances I make really define the ability.

The thing is stuff like Name, DamageType, DamageValue, & Cooldown are values that can be defined once for the ability itself and never changes after that instance is created. However, CurrentCooldown would be owner specific. If 2 actors use this ability then each would need their own instance of CurrentCooldown but not their own instance of the other fields. Yes, I COULD just make 2 instances of this Ability but there is no real need for that as those other fields won't change.

Ideally I would make a list of abilities and just make each ability 1 time, and then tell each actor which ability they have. All the details for that ability is there and will be the same and shared, but the CurrentCooldown needs to be instanced per actor.

It would be nice to be able to make some fields "owner" specific. I guess a solution would be to make a dictionary where the name of the ability the actor has is the key and the value is the cooldown for that. I'm wondering if there are other ideas around this that people have and I'm not able to think about?

答:
Don't get trapped by premature optimization.  You have to weigh any gains against the increased cost of development and maintenance.  The later of the two is the killer.

Modern computers have an incredible amount of memory.  How large is the instantiated object you are looking to deduplicate.  1KB? less? Over-engineering a system to save bytes of memory often means overly complex systems which are harder to maintain.  It usually isn't a linear tradeoff.  Even if you are God's gift to optimization as the project grows and the dev team with it there will be less experienced developers.  What is the overhead of that optimization on their productivity and accuracy.

http://blog.codinghorror.com/hardware-is-cheap-programmers-are-expensive/

The reason why this often leads to an anti-pattern is because likely your design requirements will change over time.  Elements which are static now may become not so static in the future.  The size of the duplicated data and the number of instances will factor into your decision process but lets say it is 1KB and 1,000 instances.  At most that saves you 1MB.  It sounds great until you consider that is worth about $0.02.  Ok lets say 10x that for both the size and number of instances .. still only $2.00 How much time both in development and in future maintenance did you spend over the lifetime of the project to save $2.00? My guess is >$2.00.


问:
Failover for High Frequency Jobs
I have a job that runs at a fairly high frequency (~1x every second).

This job needs to be executed constantly as long as the web app is running. However, I really only want 1 instance of the job running at a time.

Currently, I just fire up a thread that performs the job in the background, sleeping for ~800ms each loop. That causes a problem when I want redundancy, because the thread starts up as part of the app.

I know I can do something simple, like add a table in a database and have a "primary" and "secondary" server lock the record, track who's in charge, etc. But it seems a bit ugly, so I was curious if anyone had experience with a similar situation, and what solution you ended up using?

答:
The task should be running as a separate 'service' which starts when the server starts. You can use a singleton pattern to ensure there is never more than once instance running. For a .net specific solution look at Mutex. It creates a system wide singleton pattern.

While you say the process should only be running when the web app is what is really important is that the process completes some periodic work when the web app is running. It can accomplish this a number of different ways. One would be to have the service listen to see if the web app is running between sleep cycles.

The one thing you don't have is the ability to detect if the service fails to run and restart it. There are ways to accomplish that as well plus throw in alerting but if you are going to all that you should look into making your 'service' an actual windows service.

Title: Failover for High Frequency Jobs


问:
Microservices and production uptime
I have a question for people who implemented microservices in large enterprises.

There are obviously huge amount of benefits to microservices (comparatively to monolith architecture).

However, there is one thing which is problematic. It's harder to do Ops job.

In the case of monolith. There is a group of Ops engineers who make sure that production is up and running. And what is more important there are enough people to create 24/7 on call rotation. As example, if you have 15 Ops then you can create a schedule in which you have couple of persons (for redundancy) on call for a week and everybody will be scheduled only once in two month.

Now, let say a company implemented microservices and each team is responsible for it's own microservice. A team which has 4-5 engineers will still need somebody on call. And if you try to have the same couple of persons on call then they will be schedule each other week (which would be quite stressfull).

On other hand, you can't centralize Ops with microservices, because each microservice may have different technological stack, different way of troubleshooting and monitoring. So, central Ops team will be just drowning in amount of info to handle all microservices.

I heard an argument that microservices will be more stable and easily manageable. I believe it's the case. However, even increase in stability doesn't remove a need of a person to fix problems if the service went down at 3am and your company business heavily depends on it.

I am curious. How, it's handled in large enterprises?

One more suggestion was that microservices should use the same stack to allow centralized Ops. Interesting idea. However, I feel that it decrement a value (you can't choose best technologies for your microservices and have to use standard set).

答:
Microservices are much simpler than their more heavyweight counterparts like JSF, ROR, MVC, CORBA or any number of other enterprise technology acronyms.  Simpler means easier to maintain and keep running.  Node.JS and NoSQL are also part of this trend towards simpler, more decoupled architectures.

Maintenance is not the only consideration when deciding whether or not to use microservices, however.  As you correctly point out, microservices add complexity of their own accord:

Most companies don't need microservices.  Martin Fowler says:

Don't even consider microservices unless you have a system that's too complex to manage as a monolith. The majority of software systems should be built as a single monolithic application. Do pay attention to good modularity within that monolith, but don't try to separate it into separate services.

The real challenge is integration of heterogenous components into a coherent system, but this has always been the case, and that problem can be simplified by having all of the microservices conform to a REST architecture and the general simplicity of components that microservices encourages.

Title: Microservices and production uptime


问:
How does one read RFCs and similar documents?
RFC:

Request for Comments (RFC) is a memorandum published by the Internet
  Engineering Task Force (IETF) describing methods, behaviors, research,
  or innovations applicable to the working of the Internet and
  Internet-connected systems.

At the end of this Intro to REST video, RFC2616 and RFC3986 are mentioned as further reading. After watching the video, I googled those documents and, as the title suggests, I'm not sure how to use them. Do I read them in their entirety and make notes or do I use them more as a reference for when I don't understand something or have a problem?

答:
For one thing, make it easier on yourself.

Although this could perhaps be viewed as promotional spam, it's truly not meant that way:

If using Google's Chrome Browser to view ietf.org RFCs, I can recommend installing the RFCRestyle Chrome Extension for no other reason than to make the work of reading them easier on the eyes and neck.

In all seriousness, I made the extension specifically because they are daunting documents, that like it or not, MUST be read by anyone wishing to work with the web.
What better way to understand how to e.g. properly format an email, than to read the standards that shape the way the entire system works?

None that I know of.

It might not be fun or sexy, but these documents are expertly crafted, thorough examinations and revelations about every agreed procedure oiling the gears of the information age. And without trudging through them, one can only ever hope to have a layman's or (at least in some way) a corrupt understanding of the subject(s).

e.g. I built (and subsequently used) the extension after discovering Wikipedia's page about Email Addresses was less than accurate, and set about fixing it. Abundant eye strain and a lot of head scratching later, and the article was improved along with my knowledge of the subject. I had also discovered that RFCs are horrible to read without a little CSS magic.

My point?

Until I took the time to wade through the standards as defined in several RFCs, and did my best to relate that to the wiki, the readers of that wiki were provided quite severely inaccurate information;

it's only the official standards that can ultimately be relied on. Every other source of knowledge on these subjects is a corruption of the source (in some respect or other).

So, although not "the best fun EVAH!" - someone has to do it.


问:
Does the LGPL apply if I rewrite a portion of JasperReports in C++?
I would like to rewrite a portion of the JasperReports library in C++. The library will read from the same XML format used by JasperReports. If I integrate this C++ library to my proprietary application, do I need to open my C++ library source code to the end user? How does LGPL work in this scenario?</p>

答:
If you take the source code from JasperReports and translate that literally to C++, then you are creating a derived work and you are bound by the license that the original work is released under.

For a translation of a work under the LGPL license, this means that you must distribute your translation also under the LGPL (which means also providing your source code).

On the other hand, if you only study how JasperReports works when viewed from the outside and then you write a C++ library that is functionally compatible with JasperReports, then the two are completely separate works as far a copyright is concerned and you can freely choose which license you want to use for your C++ library.

As far as using the library in your proprietary application is concerned, if you dynamically link the library (or otherwise provide the means to replace it with a different version), then you can even use an LGPL library in a closed-source application without having to open up your application.


答:
There's a good book called Emotional Design: Why We Love (or Hate) Everyday Things by Donald A. Norman.  The book provides a good framework to describe and understand the less technical aspects of design.  The short version is that there are three types of reaction to any design:

Visceral - The gut reaction, it's sexy, it's polished, it's ugly.  You get the idea.

Behavioral - How the thing functions, or not as the case may be.

Reflective - How does the site make me think, react, or feel.  Recalling using the site could invoke bliss, agony, or otherwise.

I have a feeling your arguments are more on the long term reflective aspects while your clients have a more visceral reaction.  Simplicity is a very powerful concept, and very difficult to pull off well.  Basically you have to balance all the behavioral things the site needs to do while leaving a good impression.

To help prioritize what is most important, you need to think about how users will be interacting with the site.  If you are expecting short, passive interactions (like checking news), then visceral might be the most important.  However, if this is going to be used heavily for every day work, behavioral becomes paramount.  Lastly, if the site is going to be part of the face of the company, it really needs to reflect what the company is about.  An informal look can be quite appropriate if the company is projecting that image.

The best bet is to help your client become clear about their vision for the site, and how that site may or may not affect their brand.

One additional thought: You are constrained by the platform you are deploying on (as noted by your first edit).  With this constraint, it is technically infeasible to do a great number of things that would otherwise be fine to do on a fresh website.  SharePoint, being a WebForms based product does not give much leeway to customize the look and feel with it's rigid CSS, mixed CSS and embedded layout, and view state embedded in the HTML.  You can always add the element about cost into your arguments.  Between that and the argument about branding (the reflective design), you just may win them over.

Title: How do I convince my users not to use a sketch UI?

Body:
I recently worked on a prototype of a new system using Sketchflow, and now some key stakeholders are pushing for a sketched look & feel in the final product. To make matters worse, the people viewing the prototype were asked to provide feedback on the sketched look & feel by way of a fairly leading survey question, to which 80% of the responses were positive.

It's for an enterprise application that will mostly be for internal clients, but is also intended to be used by some external clients.

The main reasons I have for it thinking it's a bad idea are:

It doesn't look polished or professional

The significant effort involved in skinning an actual application in the sketched style

The sketched style doesn't make efficient use of screen real-estate

I've been trying to figure out what the appeal could possibly be, and the only thing I can come up with is that people are attracted to the simplicity of it -- especially when compared with the existing system(s) it will be replacing.

Can anyone point me in the direction of evidence of why using a sketch look & feel is a bad idea? Ideally something based on UI research. I'm worried that my voice isn't going to be listened to unless I can point to something concrete.

[Edit]

I should probably add that the difficulty of skinning the application is compounded by the fact that it is intended to be delivered as one or more Silverlight webparts in a Sharepoint site. Getting a consistent sketched look & feel across both technologies could be very difficult.

[Edit]

Just in case anyone's not sure about what a Sketchflow prototype looks like (and therefore what the people in question are asking for) they're essentially asking for a production application to have a pencil-sketch wireframe look & feel.


答:
Now, let say a company implemented microservices and each team is
  responsible for it's own microservice.

That's a fallacy. A company may implement many services from different teams, but its a single production team that will be responsible for keeping it running. That means the dev teams will have to ship enough documentation and/or tools to ensure they can do their job. Which is not much different from any other architecture.

On other hand, you can't centralize Ops with microservices, because
  each microservice may have different technological stack, different
  way of troubleshooting and monitoring

Sure, but again - this just means the documentation to keep it running needs to be more complete than if the dev team had produced a standard system using existing tools (as a 'baseline' platform would already be understood and thus not need re-documenting).

Most enterprises will only develop on a standard architecture anyway, if you're a .NET shop the team that releases a Ruby on Rails service will be unappreciated (if they are allowed to deliver such a thing in the first place).

the other aspect to maintenance is that an enterprise will also have standard monitoring requirements. So a production team will say that they expect to see logs in a certain format, with error reports in a certain template, etc. While this doesn't help with 3rd party services that are bought in, it does mitigate the maintenance cost significantly.

In short, a microservice is not carte blanche for a dev team to throw away existing standards and do whatever they feel like this week. Requirements for the service to work within the existing environment will still be specified in the original request.

Title: Microservices and production uptime

Body:
I have a question for people who implemented microservices in large enterprises.

There are obviously huge amount of benefits to microservices (comparatively to monolith architecture).

However, there is one thing which is problematic. It's harder to do Ops job.

In the case of monolith. There is a group of Ops engineers who make sure that production is up and running. And what is more important there are enough people to create 24/7 on call rotation. As example, if you have 15 Ops then you can create a schedule in which you have couple of persons (for redundancy) on call for a week and everybody will be scheduled only once in two month.

Now, let say a company implemented microservices and each team is responsible for it's own microservice. A team which has 4-5 engineers will still need somebody on call. And if you try to have the same couple of persons on call then they will be schedule each other week (which would be quite stressfull).

On other hand, you can't centralize Ops with microservices, because each microservice may have different technological stack, different way of troubleshooting and monitoring. So, central Ops team will be just drowning in amount of info to handle all microservices.

I heard an argument that microservices will be more stable and easily manageable. I believe it's the case. However, even increase in stability doesn't remove a need of a person to fix problems if the service went down at 3am and your company business heavily depends on it.

I am curious. How, it's handled in large enterprises?

One more suggestion was that microservices should use the same stack to allow centralized Ops. Interesting idea. However, I feel that it decrement a value (you can't choose best technologies for your microservices and have to use standard set).


问:
Dealing with several custom getters
I have a data structure with data units containing different types of data. I've wrapped the data in "Field" objects so that each field is able to independently parse user input in a desired way.

```<code>public abstract class<T> AField {

    protected T value = null;

    public T getValue() {
        return this.value;
    }

    // This is the main reason I'm using a custom Field class
    public abstract void parse(String data) throws ParseException;

}

public class IntegerField extends AField<Integer>{

    public void parse(String data) {
        super.value = data.trim();
    }

}

public class StringField extends AField<String> {

    ...

}

// Note this has the same type as StringField but different parse implementation
public class PhoneNumberField extends AField<String> {

    ....

}

public class DataUnit {

    private AField[] fields;
    private IntegerField number = new IntegerField();
    private StringField name = new StringField();

    public DataUnit() {
        this.fields = new Field {
            this.number,
            this.name
        }
    }

    public void parseAll(String... data) throws ParseException {
        for (int i = 0; i < this.fields.length; i++) {
            fields[i].parse(data[i]);
        }
    }

    // Now the troublesome methods

    public Integer getNumber() {
        return this.number.getValue(),
    }

    public void parseNumber(String data) throws ParseException {
        this.number.parse(data);
    }

    public String getName() {
        ...
    }

    public void parseName(String data) throws ParseException {
        ...
    }

}
</code>```

You can see how the number of methods would quickly go up as I add more types of fields to the DataUnit class or more methods to the AField class. DataUnit has to pass all the methods of all the Field classes forward because I'd rather not expose the Field objects directly to other classes. What's the best way around this method mess? Are there better patterns to achieve this?

答:
I designed and implemented a hierarchy like this many years ago (before generics) so here are some comments. They may help stop you from repeating my mistakes :)

The proliferation of methods like parseNumber(), parseName() suggests that the class hierarchy needs adjusment, yet your hierarchy looks well designed.

My approach would be a combination of techniques suggested by Robert Harvey and mdolanci.

Create an abstract class that has a parse(String data) throws ParseException method. Your AField class looks to do this now, although I would reconsider the class name (I suggest BaseField).

Create overloads for IntegerField() StringField() etc, with suitable parse logic for the type. Again this is exactly what you are doing.

Your  DataUnit class looks to be a container for an arbitrary list of fields, but has a couple of dedicated fields (number and name) that I don't quite understand. If every DataUnit must have a number and name, then they are correct. But they won't be duplicated should you add more concrete AField types like PhoneNumberField or ZipCodeField. For instance calling asZipCode() on a list of fields is incorrect, as the list might contain multiple ZipCodeField instances. You can of course add a findFirstZipCodeField() method that iterates down the field list using instanceof to find the first field of that type.

I also suggest you move the actual validation out into static methods in a separate class focussed on string validation (as suggested by @mdolanci), preferably packaged in a separate validation library that knows nothing about fields. The day will come when you want to reuse this logic in a REST interface, Android app or something you have not thought of yet. Not making this separation was one of my biggest design mistakes, and has led to unnecessary code duplication in our applications.

Title: Dealing with several custom getters


答:
Micro-services and SoA in general are cool, but they do rely on a comprehensive and resilient infrastructure.

If you havent got enough failover that you still need engineers to come out at 3am when something breaks you probably have more work to do in this area!

In my opinion, its not the 'server X has crashed emergency!' that you need to worry about with this architecture, as this can be handled with traditional fail over and redundancy.

It's the lost messages and broken orchestration between microservices which is the real extra pain over a traditional setup. '0.3% of customers don't get their order when the clocks go forward!' or 'products begining with Z aren't having the sale price modification applied!' wtfs are your new nightmare

Title: Microservices and production uptime


问:
What makes functional programming languages declarative as opposed to Imperative?
On many articles, describing the benefits of functional programming, I have seen functional programming languages, such as Haskell, ML, Scala or Clojure, referred to as "declarative languages" distinct from imperative languages such as C/C++/C#/Java. My question is what makes functional programming languages declarative as opposed to imperative.

An often encountered explanation describing the differences between Declarative and Imperative programming is that in Imperative programming you tell the computer "How to do something" as opposed to "What to do" in declarative languages. The problem I have with this explanation is that you are constantly doing both in all programming languages. Even if you go down to the lowest level assembly you are still telling the computer "What to do", you tell the CPU to add two numbers, you don't instruct it on how to perform the addition. If we go to the other end of the spectrum, a high level pure functional language like Haskell, you are in fact telling the computer how to achieve a specific task, that is what your program is a sequence of instructions to achieve a specific task which the computer does not know how to achieve alone. I understand that languages such as Haskell, Clojure, etc. are obviously higher level than C/C++/C#/Java and offer features such as lazy evaluation, immutable data structures, anonymous functions, currying, persistent data structures, etc. all which make functional programming possible and efficient, but I wouldn't classify them as declarative languages.

A pure declarative languages for me would be one which is comprised entirely of declarations only, an example of such a languages would be CSS (Yes I know CSS would technically not be a programming language). CSS just contains style declarations which are used by the HTML and Javascript of the page. CSS cannot do anything else besides make declarations, it cannot create class functions, i.e. functions which determine the style to display based on some parameter, you cannot execute CSS scripts, etc. That for me describes a declarative language (notice I did not say declarative programming language).

Update:

I've been playing around with Prolog recently and to me, Prolog is the closest programming language to a fully declarative language (At least in my opinion), if it is not the only fully declarative programming language. To elaborate programming in Prolog is done by making declarations which state either a fact (a predicate function which returns true for a specific input) or a rule (a predicate function which returns true for a given condition/pattern based on the inputs), rules are defined using a pattern matching technique. To do anything in prolog you query the knowledge base by substituting one or more of the inputs of a predicate with a variable and prolog tries to find values for the variable(s) for which the predicate succeeds.

My point is in prolog there are no imperative instructions, you basically telling (declaring) the computer what it knows and then asking (querying) about about the knowledge.  In functional programming languages you are still giving instructions i.e. take a value, call function X and add 1 to it, etc, even if you are not directly manipulating memory locations or writing out computation step by step. I wouldn't say that programming in Haskell, ML, Scala or Clojure is declarative in this sense, though I may be wrong. Is proper, true, pure functional programming declarative in the sense that I described above.

答:
You seem to be drawing a line between declaring things and instructing a machine. There is no such hard-and-fast separation. Because the machine that's being instructed in imperative programming need not be physical hardware, there is much freedom for interpretation. Almost everything can be seen as an explicit program for the right abstract machine. For example, you could see CSS as a rather high level language for programming a machine that primarily resolves selectors and sets attributes of the thus-selected DOM objects.

The question is whether such a perspective is sensible, and conversely, how closely the sequence of instructions resembles a declaration of the result being computed. For CSS, the declarative perspective is clearly more useful. For C, the imperative perspective is clearly predominant. As for languages as Haskell, well…

The language has specified, concrete semantics. That is, of course one can interpret the program as a chain of operations. It doesn't even take too much effort to choose the primitive operations so that they map nicely onto commodity hardware (this is what the STG machine and other models do).

However, the way Haskell programs are written, they frequently can sensibly be read as a description of the result to be computed. Take, for example, the program to compute the sum of the first N factorials:

```<code>sum_of_fac n = sum [product [1..i] | i <- ..n]
</code>```

You can desugar this and read it as a sequence of STG operations, but far more natural is to read it as a description of the result (which is, I think, a more useful definition of declarative programming than “what to compute”): The result is the sum the products of [1..i] for all i = 0, …, n. And that is far more declarative than almost any C program or function.

Body:
You seem to be drawing a line between declaring things and instructing a machine. There is no such hard-and-fast separation. Because the machine that's being instructed in imperative programming need not be physical hardware, there is much freedom for interpretation. Almost everything can be seen as an explicit program for the right abstract machine. For example, you could see CSS as a rather high level language for programming a machine that primarily resolves selectors and sets attributes of the thus-selected DOM objects.

The question is whether such a perspective is sensible, and conversely, how closely the sequence of instructions resembles a declaration of the result being computed. For CSS, the declarative perspective is clearly more useful. For C, the imperative perspective is clearly predominant. As for languages as Haskell, well…

The language has specified, concrete semantics. That is, of course one can interpret the program as a chain of operations. It doesn't even take too much effort to choose the primitive operations so that they map nicely onto commodity hardware (this is what the STG machine and other models do).

However, the way Haskell programs are written, they frequently can sensibly be read as a description of the result to be computed. Take, for example, the program to compute the sum of the first N factorials:

sum_of_fac n = sum [product [1..i] | i <- ..n]

You can desugar this and read it as a sequence of STG operations, but far more natural is to read it as a description of the result (which is, I think, a more useful definition of declarative programming than “what to compute”): The result is the sum the products of [1..i] for all i = 0, …, n. And that is far more declarative than almost any C program or function.


问:
Database Normalization vs dependencies
I am developing 3-4 interdependent programs.  Call them foo bar baz and auth.  I want them to be independent of each other.  Imagine if I were to license out each program to other companies.  Some companies may want foo and bar, others may just want baz, etc.  It also seems like good practice to keep auth independent as well.

Context:
auth is taking care of authentication for all of the systems.  The main users table in auth has user_id, email, password, first, last

foo has a users table as well which has specific fields for the application:
user_id, role_id, etc.

Each system has its own database.  In the past I have created a foreign key from each application to the auth db.  I removed update permissions from the other dbs but granted select access to certain relevant fields.  This seems like a bad solution because it creates a tight dependency, but it allowed me to normalize the db so that I didn't have to store the users name and email in the foo, bar, or baz databases.

Would it be better to store the information in all of the databases?  Or would it be better to store the Auth Id in foo bar and baz and use an api to get the user info using the authId?

Similarly, I might have customers in all 3 systems.  Sure it seems bad to create a dependency into an auth db, but what about the customer dbs across all 3 of them?

Or is the best solution to have one central db.  One users table.

Other Suggestions?

答:
Your example is a bit abstract, but let me run through my thoughts.

Option A : In my experience this is Always Bad regardless of your reasons. sure DBs like MSSQL can have friend databases etc, but if the data is linked, it should be in the same DB

Option B : Not sure whats going on in here, you are adding an API which queries all DBs and brings the results together? This is Better, but if you have Apps on top of that API then its part of the datalayer for them and they really only use one of the DBs, so why have they got the others in thier data layer?

Option C : Well this works, but its not good to have one big database with unrelated data in it. You want the programs to be independent of each other right? this dosnt help with that.

Option D

My suggestion is to abstract the authentication away form the concept of userId. your Auth App should be concerned with users and roles (or promises etc if your are going all modern) this data should exist in the Auth DB

Each App needs to have a userId to group data by user, with some related data to make the auth call and identify the user to humans. this would be userId (unique to the app), real name, authusername, auth service to use. This data should exist on the apps DB

The databases should have no connection between them, conceptually you should be able to use facebook as your auth service rather that your Auth App

You may need a Further User linking information if you want to relate a foo user with a bar user

Title: Database Normalization vs dependencies


问:
What arguments are there to use a coding style for each distinct language?
I recently had a discussion about our coding style for C# projects. Two things in particular were very hard to agree upon.

Method Naming

C# has the de-facto standard of naming (at least public, not sure about private) methods in the PascalCase. Coming from a Java background, our current document states to use camelCase instead.

Curly Bracket Placement

Visual Studio by default places every curly bracket in its own line. I don't have a source, but I can think this is also used throughout the industry as a guideline for coding style. Again, due to the Java background, our current policy is to rather write if (...) { (same line).

When I raise these issues and non-compliance to (IMHO) standards of the C# industry, I often hear the argument "we won't use different styles for different languages, so every code looks the same".

I think this argument, while it does make sense in some way, is invalid to the discussion. Should you treat every language the same when creating a guide for your code, or use the standards of the industry around that language as a guide instead?

Unfortunately, I don't have any good counter-arguments, besides "it's what everybody else does".

What can I do to push the coding style in the (for me) "right" direction? That is towards what everybody else already does in the industry?

PS: Main languages are Java, C++, C# and JavaScript

答:
There is a case for different styles for each language - it helps you remember that you're writing something different, and thus will help to prevent some subtle errors due to language similarities (ie where you are still thinking Java techniques when writing C# code and vice-versa).

It can slow you down a little when switching, but frankly - this is a good thing. Stopping to context switch is better than diving in and coding without due care.

Personally, I always go with the "whatever style the code is currently written in is the style to use". So occasionally when I work on certain 3rd party code that had used a particular idiom, I maintain that god-awful style.


答:
If you have 4 independant services, then they have to independant. No data should be shared in common DBs or similar, as then you simply make them dependant!

Now while its OK to share a single DB in production, the services should use their own schemas as to DB is just there as a common container, similar to how a single Linux server can run all 4 services.

Each service should have its own API, and this is the only way to get data in and out of each. So your auth service will store users and perform authentication, but will return some token to identify a user. This token is what the other services use to remember which user is which - but otherwise they should have no knowledge of user authentication at all.

The easiest way to think of implementing these is to think what would you do if you decided to use a 3rd party service instead of the ones you're writing - if you used StackExchange's OpenID service for users instead of your own. If you can replace that into your architecture then you have a good, independent design.

Title: Database Normalization vs dependencies

Body:
I am developing 3-4 interdependent programs.  Call them foo bar baz and auth.  I want them to be independent of each other.  Imagine if I were to license out each program to other companies.  Some companies may want foo and bar, others may just want baz, etc.  It also seems like good practice to keep auth independent as well.

Context:
auth is taking care of authentication for all of the systems.  The main users table in auth has user_id, email, password, first, last

foo has a users table as well which has specific fields for the application:
user_id, role_id, etc.

Each system has its own database.  In the past I have created a foreign key from each application to the auth db.  I removed update permissions from the other dbs but granted select access to certain relevant fields.  This seems like a bad solution because it creates a tight dependency, but it allowed me to normalize the db so that I didn't have to store the users name and email in the foo, bar, or baz databases.

Would it be better to store the information in all of the databases?  Or would it be better to store the Auth Id in foo bar and baz and use an api to get the user info using the authId?

Similarly, I might have customers in all 3 systems.  Sure it seems bad to create a dependency into an auth db, but what about the customer dbs across all 3 of them?

Or is the best solution to have one central db.  One users table.

Other Suggestions?


答:
I'd say if your Java devs regularly program in C# and vice versa, they might have some argument for making them look the same (slightly easier to read).

But even then, differences can be useful enough to trump reading ease. I for one like to use same-line-open-brackets in JavaScript to remind my brain at all times that the code I'm looking at is not C#.

Otherwise, it's none of their business what the C# devs use.

On the contrary, it's important that the C# devs keep conventions that are easy for interacting with other C# devs, reading and posting C# code online, etc.

Good candidates will be reluctant to work at a place with such a silly mis-application of coding conventions.

Title: What arguments are there to use a coding style for each distinct language?

Body:
I recently had a discussion about our coding style for C# projects. Two things in particular were very hard to agree upon.

Method Naming

C# has the de-facto standard of naming (at least public, not sure about private) methods in the PascalCase. Coming from a Java background, our current document states to use camelCase instead.

Curly Bracket Placement

Visual Studio by default places every curly bracket in its own line. I don't have a source, but I can think this is also used throughout the industry as a guideline for coding style. Again, due to the Java background, our current policy is to rather write if (...) { (same line).

When I raise these issues and non-compliance to (IMHO) standards of the C# industry, I often hear the argument "we won't use different styles for different languages, so every code looks the same".

I think this argument, while it does make sense in some way, is invalid to the discussion. Should you treat every language the same when creating a guide for your code, or use the standards of the industry around that language as a guide instead?

Unfortunately, I don't have any good counter-arguments, besides "it's what everybody else does".

What can I do to push the coding style in the (for me) "right" direction? That is towards what everybody else already does in the industry?

PS: Main languages are Java, C++, C# and JavaScript

ContentLicense: CC BY-SA 4.0


问:
What techniques do you use when interviewing developers?
I realize there have been lots of discussions about this type of thing and they often devolve into dogma around whether you ask the "100 logical pirates" type of questions or whether you get them to write "fizz buzz".

I'm interested in what techniques and questions have been effective for you when interviewing potential developers for jobs.

One technique per answer so we can vote on them, please.

答:
Have several people from your team interview them independently.  Share your thoughts after, don't talk in between before interviewing them.  Talking in between will sway your judgement and you won't have independent assesements.

For the technical people interviewing them make them write code. For non technical, don't try to ask things you aren't experienced with.  Make sure you have at least some technical people interviewing though.

Interviews should not be conducted only by managers, it should be extremely important to every worker who they will work with in the future.


问:
Refactoring long methods with a lot of cyclomatic complexity
I'm attempting to refactor what is becoming a very large method -- currently 350 or so lines -- that contains a high degree of cyclomatic complexity.

I understand and ascribe to the theories that methods should be short and that concerns should be separated, and I've been reading over things like this and this among others.  I'm struggling to refactor my method, though, for a couple of reasons.  To help illustrate these, first here is a simplified example of what the method looks like before refactoring:

```<code>private static void ProcessMessage(Message toProcess)
{
    var processingIssues = new StringBuilder();
    var transformedAttachments = new List<TransformedAttachmentData>();

    foreach (var attach in toProcess.Attachments)
    {
        //in reality there is quite a bit of nested logic here,
        //but I'll represent it as a single if-else block.
        if (true)
        {
            //in reality, a third-party library is used in multiple
            //levels of this logic hierarchy to produce the transformed data.
            transformedAttachments.Add(new TransformedAttachmentData(attach));
        }
        else
        {
            processingIssues.AppendLine(
                string.Format(@"Issue ""{0}"" occurred with " +
                @"attachment ""{1}"".", "blah blah problem", attach.Name));
        }
    }

    /*
     * do something else complex here with
     * processingIssues and validResults
     */
}
</code>```

First, the very cyclomatic complexity which is concerning to me is born of a complicated set of business rules that need to be applied which together sum up to a couple shared sets of data (represented here as processingIssues and transformedAttachments).  Basically what this means to me is that not only should I break the foreach out into its own method, but I should also further consider breaking the logic tree contained within it into additional methods in the interest of keeping my methods "short".  In other words, it would seem as though it's not enough just to break my current method into its two obvious outer-most parts: "pre-processing" and "post-processing" of the attachments, if you will.  How far do I need to go with this given that I am dealing with a complicated logic tree with concerns that are not so "separate" from one another.  In other words, if "separation of concerns" is one reason to refactor to smaller methods, but so is "cyclomatic complexity" -- both of which seem to be orthogonal concepts -- which is the "right" reason to refactor, and how should I do it in the latter case?

Second, in order to separate out some of the concerns to separate methods, those separate methods will have to return multiple variables (again, processingIssues and transformedAttachments), both of which are only needed within the separate methods themselves, so I'm faced with the choice: use output parameters, or create a small class to wrap the return values.  Which is better?

Any guidance on this topic and my specific hang-ups would be much appreciated.

答:
I would post the whole function to code review.

But, here are my views on your snippet and questions from an OOP view point:

static ProcessMessage should be message.GetTransformedAttachments() and TransformedAttachment.Process()

if (logic) should be attach.IsLogicTrue

TransformedAttachmentData(attach) should be attach.GetTransformedData()

So thats 3 more methods already!

If you create the mini classes you need to return multiple values from the functions, and then move the functions to those classes, you can then use inheritance to remove conditional statements in the logic. This will reduce the length of your code (in methods) and cyclelowhatsit complexity.

your method could end up just being,

```<code>for each x in y
   x.doSomething
</code>```

if x is subclassed enough you have no if statements and the object graph takes care of all your outputs!

note: I'm not saying this is the best solution. A service class with a ton of ifs can sometimes be good if it matches the business definition of the process and lots of inheritance can make debugging a pain in the ass. But you should def give it a go and see if you like it.

Body:
I would post the whole function to code review.

But, here are my views on your snippet and questions from an OOP view point:

static ProcessMessage should be message.GetTransformedAttachments() and TransformedAttachment.Process()

if (logic) should be attach.IsLogicTrue

TransformedAttachmentData(attach) should be attach.GetTransformedData()

So thats 3 more methods already!

If you create the mini classes you need to return multiple values from the functions, and then move the functions to those classes, you can then use inheritance to remove conditional statements in the logic. This will reduce the length of your code (in methods) and cyclelowhatsit complexity.

your method could end up just being,

for each x in y
   x.doSomething

if x is subclassed enough you have no if statements and the object graph takes care of all your outputs!

note: I'm not saying this is the best solution. A service class with a ton of ifs can sometimes be good if it matches the business definition of the process and lots of inheritance can make debugging a pain in the ass. But you should def give it a go and see if you like it.


答:
Unfortunately, I don't think there is any way to achieve your goal. Your workplace has made Java the first-class language and culture, and made C# second-class. Trying to raise this issue will possibly make you an unfavorable person among the coworkers.

That particular coding style may also have the backing of some senior staff in the company. Given that the workplace is already rife with politics, raising this issue alone may be detrimental to one's career.

Also, for a code base that is entirely internal to one company,  coding styles that are purely cosmetic in nature can be chosen to go against the industry norm as long as it is consistently applied. (By saying it is cosmetic, it means the style is harmless to code quality). Since consistency is important, the existing coding style will prevail, so your goal will not be achievable.

However, if the company makes heavy use of third-party source code, maintaining the naming consistency in each language will become more difficult. (This difficulty does not affect the curly braces because its effects are not visible on the surface of an API (programming interface).)

If the company's code base does not use third-party source code at all (which could be true for some sufficiently large companies), or if the team decides to write wrappers for every single third-party component so as to normalize the method naming according to the internal standard (which is also a common practice in many companies), then the heavy use of third-party source code will not provide a strong reason for following the industry naming convention.

When all things considered, my inclination is that Ewan's answer is the only one applicable to your situation, and that other persuasions will probably be defeated in a logical debate.

All things aside, there is one technicality when JNI is involved. (JNI is used to allow Java code to call into C++ code. Since both languages are mentioned by OP, it is likely that JNI is on the radar when the company's coding standard is drafted.)

JNI requires the C/C++ native method entry points to be named in a particular way. This is enforced by the Java runtime, which will concatenate the Java class name and method name in a prescribed manner, and then look up the JNI entry point. For this reason, it is possible that developers who work on JNI components need to prescribe a naming convention that is to be applied to both the Java methods and the C++ counterparts.


问:
Correct placement of Methods in OOP
Which Class should contain a method which has dependencies on multiple classes?

I've coded up a specific example to avoid generalizations. In this example we have an initial requirement :

customers have accounts and can purchase orders, which contain items.

The application is coded up as per OOP principles. Since the purchase requires an account, which is owned by a customer and the requirement is phrased in terms of a customer making a purchase, customer seems like a good place to put it.

However :

Added Requirement : An advance order can be reserved by a customer if
  they have enough funds and purchased at a later date. an advance order
  can't be purchased if it has not been reserved.

Once we add the logic for the advance order the placement of the method on customer seems less certain. We had to re-factor quite a bit to get it in and have a duplicate method 'Purchase' on Order

Is having Purchase on Customer consistent with OOP principles and good design? Or is there a better place to put it, do we need a new class?

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace OOP
{
#region Repository Assembly
    public class OrderRepository : IOrderRepository
    {
        public void Add(Order order) { }
    }
    public class AccountRepository : IAccountRepository
    {
        public void Update(Account account) { }
    }
#endregion

#region Models Assembly
    public interface IOrderRepository
    {
        void Add(Order order);
    }

    public interface IAccountRepository
    {
        void Update(Account account);
    }

    public class Customer
    {
        public string Id { get; private set; }
        public string Name { get; private set; }
        public Account Account { get; private set; }

        public Customer(Account account)
        {
            this.Account = account;
        }

        public void Purchase(Order order)
        {
            if (Account.HasFundsAvailable(order.TotalPrice()))
            {
                Account.Debit(order.TotalPrice());
                order.Purchase();
            }
            else
            {
                throw new Exception("not enough funds in account");
            }
        }

        /// added code
        public void Purchase(AdvanceOrder order)
        {
            if (!order.IsReserved())
            {
                throw new Exception("must reserve advanced orders");
            }
            if (Account.HasFundsAvailable(order.TotalPrice()))
            {
                order.Purchase();
            }
            else
            {
                throw new Exception("not enough funds in account");
            }
        }

        /// added code
        public void Reserve(AdvanceOrder order)
        {
            if (Account.HasFundsAvailable(order.TotalPrice()))
            {
                order.Reserve();
            }
            else
            {
                throw new Exception("not enough funds in account");
            }
        }
    }

    public class Account
    {
        private IAccountRepository rep;
        public string Id { get; private set; }
        public string CustomerId { get; private set; }
        public decimal Balance { get; private set; }

        public List<Transaction> Transactions { get; private set; }

        public Account(IAccountRepository rep, decimal balance, List<Transaction> Transactions)
        {
            this.rep = rep;
            this.Balance = balance;
            this.Transactions = Transactions;
        }

        public bool HasFundsAvailable(decimal amount)
        {
            if (this.Balance >= amount)
            {
                return true;
            }
            return false;
        }

        public void Debit(decimal amount)
        {
            if (this.HasFundsAvailable(amount))
            {
                Transaction t = new Transaction(amount);
                this.Transactions.Add(t);
                this.rep.Update(this);
            }
            else
            {
                throw new Exception("not enough funds");
            }
        }
    }

    public class Transaction
    {
        public Transaction(decimal amount)
        {
            this.Amount = amount;
        }
        public string Id { get; private set; }
        public decimal Amount { get; private set; }
    }

    public class Order
    {
        protected IOrderRepository rep;
        public string Id { get; private set; }
        public string Status { get; protected set; }
        public IEnumerable<Item> Items { get; private set; }

        public Order(IOrderRepository rep, string status, List<Item> items)
        {
            this.rep = rep;
            this.Status = status;
            this.Items = items;
        }

        public decimal TotalPrice()
        {
            return this.Items.Sum(i => i.Price);
        }

        public void Purchase()
        {
            this.Status = "Purchased";
            this.rep.Add(this);
        }
    }

    /// added code
    public class AdvanceOrder : Order
    {
        public AdvanceOrder(IOrderRepository rep, string status, List<Item> items)
            : base(rep, status, items)
        {
        }
        public void Reserve()
        {
            this.Status = "Reserved";
            this.rep.Add(this);
        }
        public bool IsReserved()
        {
            return this.Status == "Reserved";
        }
    }

    public class Item
    {
        public string Id { get; private set; }
        public string Name { get; private set; }
        public decimal Price { get; private set; }

        public Item(string name, decimal price)
        {
            this.Name = name;
            this.Price = price;
        }
    }
#endregion

    [TestClass]
    public class Tester
    {
        [TestMethod]
        public void PurchaseTest()
        {
            IOrderRepository orderRep = new OrderRepository();
            Item i = new Item("test",(decimal)10.2);
            List<Item> items = new List<Item>();
            items.Add(i);
            Order o = new Order(orderRep, "new", items);

            IAccountRepository accountRep = new AccountRepository();
            Account a = new Account(accountRep, (decimal)100, new List<Transaction>());

            Customer c = new Customer(a);

            c.Purchase(o);

            Assert.AreEqual("Purchased", o.Status);
        }

        [TestMethod]
        public void ReserveTest()
        {
            IOrderRepository orderRep = new OrderRepository();
            Item i = new Item("test", (decimal)10.2);
            List<Item> items = new List<Item>();
            items.Add(i);
            AdvanceOrder o = new AdvanceOrder(orderRep, "new", items);

            IAccountRepository accountRep = new AccountRepository();
            Account a = new Account(accountRep, (decimal)100, new List<Transaction>());

            Customer c = new Customer(a);

            c.Reserve(o);

            Assert.AreEqual("Reserved", o.Status);

            c.Purchase(o);

            Assert.AreEqual("Purchased", o.Status);
        }
    }
}
</code>```

答:
Is having Purchase on Customer consistent with OOP principles and good
  design? Or is there a better place to put it, do we need a new class?

No, it is not, and yes you need a new class. A purchase indicates that there is data to be persisted, and the Customer object should not know about data persistence pertaining to an order, or even about what is being ordered.

Typically you will have a service object that knows how to place an order, so the code becomes:

```<code>orderService.placeOrder(Customer customer, Shopping cart cart);
</code>```

Title: Correct placement of Methods in OOP

Body:
Is having Purchase on Customer consistent with OOP principles and good
  design? Or is there a better place to put it, do we need a new class?

No, it is not, and yes you need a new class. A purchase indicates that there is data to be persisted, and the Customer object should not know about data persistence pertaining to an order, or even about what is being ordered.

Typically you will have a service object that knows how to place an order, so the code becomes:

orderService.placeOrder(Customer customer, Shopping cart cart);


问:
If a variable has getter and setter, should it be public?
I have a class with a variable that is private and the class has a getter and a setter for that variable. Why not make that variable public?

The only case I think you have to use getters and setters is if you need to do some operation besides the set or the get. Example:

```<code>void my_class::set_variable(int x){
   /* Some operation like updating a log */
   this->variable = x;
}
</code>```

答:
You say "The only case I think you have to use getters and setters is if you need to do some operation besides the set or the get. ".

You should use getters and setters if at some point in the future you might need to do some operation besides the set and get and you don't want to change thousands of lines of source code when that happens.

You should use getters and setters if you don't want someone to take the address of the variable and pass it around, with disastrous consequences if that variable can then be changed without any source code mentioning it, or even after the object stopped existing anymore.


问:
Memento pattern: saving memento
There is one problem about this pattern that troubles me.

In a situation when we have to save a state into a file, is it class Memento that should be responsible for handling this process? (for example, providing SaveToFile and RestoreFromFile functions)

答:
Short answer: No.

Long answer:

Think back to the Single Responsibility Principle. An object (or method, or module) should only have one reason to exist. That reason may be large or small, but it is cohesive. A memento exists to manage temporal state. In other words, track state as it changes, to allow moving backward and forward through those states. The goal of the memento pattern is essentially to enable chaining undo/redo (ctrl+Z/ctrl+Y) operations.

Those mementos may be serializable and the originator may also be serializable. Those serialized forms may be suitable for saving to disk, memory buffer, printing on paper, whatever you want: but the memento itself is not concerned with saving anything to disk. That is not its responsibility.

While an object may know how to serialize and deserialize itself1, generally the action of actually saving or loading to/from disk or anything else is the responsibility of another object. That is the idea behind "serialization": it is a very broad interface between any object that has a potential need to copy itself to another location, and objects responsible for communicating with those locations.

This is typically done with streams. Serialization really just means "convert this object into a string of bytes or characters" which a stream can then consume. The stream could be a file stream for saving/loading to/from a file on disk, the network, etc. It could be backed by a socket, HTTP, a web service, anything. The memento does not need to know what a "disk" is or what a "file" is.

1 While it may be appropriate for a simple object or a single object to manage its own serialization, a complex object or a module with a lot of objects (e.g. a group of DAOs) may be better served with objects that manage serialization for them. There is overhead associated with this, and it only makes sense to spend the time and effort when it makes the system design clearer.

Title: Memento pattern: saving memento


问:
Python rectangle packing
I'm working on a project which involves packing multiple rectangles in a larger rectangle(the bounding box). Rectangles can't overlap with each other or with the boundaries of the bounding box. Rectangles can rotate, increasing the state space to n! * 2^n for problems of n rectangles.

I'm trying to write a Python program that 'solves' these problems, eg it should find all possible solutions given a set of rectangles and a bounding box. I'm using a depth-first search algorithm right now, but I feel like I'm missing a lot of optimisations to speed up my program. My algorithm works as follows:

I have a list with values representing the heights of the columns in the larger bounding box, initialised to all 0's.

I look for the first empty spot in the bounding box, which is represented by the column with the smallest value.

If the current rectangle fits in that spot, I 'place' the rectangle by increasing the height of the right columns by the height of the rectangle.

Repeat 2 and 3 until no more rectangles can be fit and backtrack to other possible solutions.

In (pseudo-)code it looks like this:

```<code>def solve(rectangles):

    # Solution found
    if rectangles is empty:
        add_to_solutions()
        return

    position = find_first_empty_spot()
    for rectangle in rectangles:
        for r in [rectangle, rectangle.rotated()]:
            if rectangle fits at given position:
                place_rectangle_in_bounding_box(r)
                remove r from rectangles
                solve(remaining_rectangles)
                remove_rectangle_from_bounding_box(r)
</code>```

Are the basics of my algorithm correct or am I missing some (obvious) improvements? It would be great to solve problems of sizes up to 20 rectangles but my current algorithm would take way too much time to solve them.

And: I'm trying to find 'all' possible solutions to the problem, I can't just stop after finding 'a' solution, so a lot of heuristics found in the literature are not applicable.

答:
The problem you are asking about is a well known problem which has a plethora of applications:  For example the task to minimize material waste in furniture production: Certain pieces (your list of rectangles) have to be cut out of boards of plywood in a given size (your bounding rectangle).  As you seem to have already figured out finding all possible solutions is a combinatorial NP-hard problem.

Therefore in the industry we usually don't insist on finding all possible solutions but instead use an approximation algorithm which might of course not always deliver the best possible solution.  So currently the best answer I can give to your question is to point you to this BPP example here illustrating the use of a solver from the open source Python OpenOpt package.

From my understanding your wish to enumerate all possible solutions is impossible to fulfill in an acceptable time even for a moderate number of saying 20 rectangles or so.  If this is not true I'm also eager to know and learn.

OwnerDisplayName: Koen

Title: Python rectangle packing


答:
You are right that there is no clear distinction between telling the computer what to do and how to do it.

However, on one side of the spectrum you almost exclusively think about how to manipulate memory. That is, to solve a problem, you present it to the computer in a form like "set this memory location to x, then set that memory location to y, jump to memory location z ..." and then somehow you end up having the result in some other memory location.

In managed languages like Java, C# and so on, you don't have a direct access to the hardware memory anymore. The imperative programmer is now concerned with static variabes, references or fields of class instances, all of which are to some degree absractions for memory locations.

In langugaes like Haskell, OTOH, memory is completely gone away. It is simply not the case that in

```<code>f a b = let y = sum [a..b] in y*y
</code>```

there must be two memory cells that hold the arguents a and b and another one that holds the intermediate result y. To be sure, a compiler backend could emit final code that works this way (and in some sense it must do so as long as the target architecture is a v. Neumann machine).

But the point is we don't need to internalize the v. Neumann architecture to understand the above function. Nor do we need a contemporary computer to run it. It would be easy to translate programs in a pure FP language to a hypothetical machine that works on the base of the SKI calculus, for instance. Now try the same with a C program!

A pure declarative languages for me would be one which is comprised entirely of declarations only

This is not strong enough, IMHO. Even a C program is just a sequence of declarations. I feel we must qualify the declarations further. For example, are they telling us what something is (declarative) or what it does (imperative).

Title: What makes functional programming languages declarative as opposed to Imperative?

Body:
On many articles, describing the benefits of functional programming, I have seen functional programming languages, such as Haskell, ML, Scala or Clojure, referred to as "declarative languages" distinct from imperative languages such as C/C++/C#/Java. My question is what makes functional programming languages declarative as opposed to imperative.

An often encountered explanation describing the differences between Declarative and Imperative programming is that in Imperative programming you tell the computer "How to do something" as opposed to "What to do" in declarative languages. The problem I have with this explanation is that you are constantly doing both in all programming languages. Even if you go down to the lowest level assembly you are still telling the computer "What to do", you tell the CPU to add two numbers, you don't instruct it on how to perform the addition. If we go to the other end of the spectrum, a high level pure functional language like Haskell, you are in fact telling the computer how to achieve a specific task, that is what your program is a sequence of instructions to achieve a specific task which the computer does not know how to achieve alone. I understand that languages such as Haskell, Clojure, etc. are obviously higher level than C/C++/C#/Java and offer features such as lazy evaluation, immutable data structures, anonymous functions, currying, persistent data structures, etc. all which make functional programming possible and efficient, but I wouldn't classify them as declarative languages.

A pure declarative languages for me would be one which is comprised entirely of declarations only, an example of such a languages would be CSS (Yes I know CSS would technically not be a programming language). CSS just contains style declarations which are used by the HTML and Javascript of the page. CSS cannot do anything else besides make declarations, it cannot create class functions, i.e. functions which determine the style to display based on some parameter, you cannot execute CSS scripts, etc. That for me describes a declarative language (notice I did not say declarative programming language).

Update:

I've been playing around with Prolog recently and to me, Prolog is the closest programming language to a fully declarative language (At least in my opinion), if it is not the only fully declarative programming language. To elaborate programming in Prolog is done by making declarations which state either a fact (a predicate function which returns true for a specific input) or a rule (a predicate function which returns true for a given condition/pattern based on the inputs), rules are defined using a pattern matching technique. To do anything in prolog you query the knowledge base by substituting one or more of the inputs of a predicate with a variable and prolog tries to find values for the variable(s) for which the predicate succeeds.

My point is in prolog there are no imperative instructions, you basically telling (declaring) the computer what it knows and then asking (querying) about about the knowledge.  In functional programming languages you are still giving instructions i.e. take a value, call function X and add 1 to it, etc, even if you are not directly manipulating memory locations or writing out computation step by step. I wouldn't say that programming in Haskell, ML, Scala or Clojure is declarative in this sense, though I may be wrong. Is proper, true, pure functional programming declarative in the sense that I described above.

Body:
You are right that there is no clear distinction between telling the computer what to do and how to do it.

However, on one side of the spectrum you almost exclusively think about how to manipulate memory. That is, to solve a problem, you present it to the computer in a form like "set this memory location to x, then set that memory location to y, jump to memory location z ..." and then somehow you end up having the result in some other memory location.

In managed languages like Java, C# and so on, you don't have a direct access to the hardware memory anymore. The imperative programmer is now concerned with static variabes, references or fields of class instances, all of which are to some degree absractions for memory locations.

In langugaes like Haskell, OTOH, memory is completely gone away. It is simply not the case that in

f a b = let y = sum [a..b] in y*y

there must be two memory cells that hold the arguents a and b and another one that holds the intermediate result y. To be sure, a compiler backend could emit final code that works this way (and in some sense it must do so as long as the target architecture is a v. Neumann machine).

But the point is we don't need to internalize the v. Neumann architecture to understand the above function. Nor do we need a contemporary computer to run it. It would be easy to translate programs in a pure FP language to a hypothetical machine that works on the base of the SKI calculus, for instance. Now try the same with a C program!

A pure declarative languages for me would be one which is comprised entirely of declarations only

This is not strong enough, IMHO. Even a C program is just a sequence of declarations. I feel we must qualify the declarations further. For example, are they telling us what something is (declarative) or what it does (imperative).


答:
The basic unit of an imperative program is the statement.  Statements are executed for their side effects.  They modify the state they receive.  A sequence of statements is a sequence of commands, denoting do this then do that.  The programmer specifies the exact order to perform the computation.  This is what people mean by telling the computer how to do it.

The basic unit of a declarative program is the expression.  Expressions do not have side effects.  They specify a relationship between an input and output, creating a new and separate output from their input, rather than modifying their input state.  A sequence of expressions is meaningless without some containing expression specifying the relationship between them.  The programmer specifies the relationships between data, and the program infers the order to perform the computation from those relationships.  This is what people mean by telling the computer what to do.

Imperative languages have expressions, but their primary means of getting things done is statements.  Likewise, declarative languages have some expressions with semantics similar to statements, like monad sequences inside Haskell's do notation, but at their core, they are one big expression.  This lets beginners write code that is very imperative-looking, but the true power of the language comes when you escape that paradigm.