答: I can't name any open-source projects that used TDD, but I can tell you that I've worked on real-world projects where TDD was used...and was a lifesaver!</p>

Title: Good example of complex code using TDD


问:
Updating password hashing without forcing a new password for existing users
You maintain an existing application with an established user base. Over time it is decided that the current password hashing technique is outdated and needs to be upgraded. Furthermore, for UX reasons, you don't want existing users to be forced to update their password. The whole password hashing update needs to happen behind the screen.

Assume a 'simplistic' database model for users that contains:

ID

Email

Password

How does one go around to solving such a requirement?

My current thoughts are:

create a new hashing method in the appropriate class

update the user table in the database to hold an additional password
field

Once a user successfully logs in using the outdated password hash, fill the second password field with the updated hash

This leaves me with the problem that I cannot reasonable differentiate between users who have and those who have not updated their password hash and thus will be forced to check both. This seems horribly flawed.

Furthermore this basically means that the old hashing technique could be forced to stay indefinitely until every single user has updated their password. Only at that moment could I start removing the old hashing check and remove the superfluous database field.

I'm mainly looking for some design tips here, since my current 'solution' is dirty, incomplete and what not, but if actual code is required to describe a possible solution, feel free to use any language.

答:
Your solution (additional column in the database) is perfectly acceptable. The only issue with it is the one you already mentioned: that the old hashing is still used for users who haven't authenticated since the change.

In order to avoid this situation, you may wait for your most active users to switch to the new hashing algorithm, then:

Remove the accounts of users who haven't authenticate for too long. There is nothing wrong in removing an account of a user who never came to the website for three years.

Send an email to the remaining users among those who haven't authenticated for a while, telling that they may be interested in something new. It will help to further reduce the number of accounts which use the older hashing.

Be careful: if you have a no-spam option users can check on your website, don't send the email to users who checked it.

Finally, a few weeks after the step 2, destroy the password for the users who are still using the old technique. When and if they try to authenticate, they'll see that their password is invalid; if they are still interested in your service, they could reset it.

ContentLicense: CC BY-SA 3.0


问:
Authenticate native mobile app using a REST API
I'm starting a new project soon, which is targeting mobile application for all major mobile platforms (iOS, Android, Windows). It will be a client-server architecture.

The app is both informational and transactional. For the transactional part, they're required to have an account and log in before a transaction can be made. I'm new to mobile development, so I don't know how the authentication part is done on these platforms. The clients will communicate with the server through a REST API. Will be using HTTPS ofcourse.

I haven't yet decided if I want the user to log in when they open the app, or only when they perform a transaction.

I got the following questions:

1) Like the Facebook application, you only enter your credentials when you open the application for the first time. After that, you're automatically signed in every time you open the app. How does one accomplish this? Just simply by encrypting and storing the credentials on the device and sending them every time the app starts?

2) Do I need to authenticate the user for each (transactional) request made to the REST API or use a token based approach?

Please feel free to suggest other ways for authentication.

Thanks!

答:
You pass username/password to the login method of your RESTful API and it returns access-token. That access token is just some unique (for the system) string.

Device stores (persists) that access-token. Each time you send RESTful request to the server you put that access-token in header of HTTP request. Server finds the user by access-token and on success fulfills the request.

username/password must not be stored on the device.


问:
What is the right level of site blocking for you as a developer?
Almost all developers who work for a large corporation find themselves on the wrong side of site blocking software. It can be both frustrating ("Just let me read that damn blog!") and helpful ("Woah! Dodged a bullet with that site").

In your opinion, what is the right level of blocking to apply to developers and why?

答:
Blocking sites like blogs and google images do not help, sometimes/often answers to problems you have (or if you just forget something) are on sites like these.

If your developers are just spending their time of Facebook and not producing anything, then they don't seem to care they have a job. Ultimately they wouldn't be a programmer if they didn't enjoy it. Having said that Facebook and such sites shouldn't be blocked because there are times when you just need to clear your head.

And I don't see how you can know "Woah dodge a bullet there" if the sites blocked and you'll never know what the site is.

And there's generally a way around it, from simply using a different language, to use the IP Address, to hitting Esc/Stop at the right time (depending on how useless the blocking software is, cough older version of Impero cough) to using a proxy. So more time will be wasted on getting around the blocking than if the site was unblocked

ContentLicense: CC BY-SA 2.5


问:
How do we keep dependent data structures up to date?
Suppose you have a parse tree, an abstract syntax tree, and a control flow graph, each one logically derived from the one before. In principle it is easy to construct each graph given the parse tree, but how can we manage the complexity of updating the graphs when the parse tree is modified? We know exactly how the tree has been modified, but how can the change be propagated to the other trees in a way that doesn't become difficult to manage?

Naturally the dependent graph can be updated by simply reconstructing it from scratch every time the first graph changes, but then there would be no way of knowing the details of the changes in the dependent graph.

I currently have four ways to attempt to solve this problem, but each one has difficulties.

Nodes of the dependent tree each observe the relevant nodes of the original tree, updating themselves and the observer lists of original tree nodes as necessary. The conceptual complexity of this can become daunting.

Each node of the original tree has a list of the dependent tree nodes that specifically depend upon it, and when the node changes it sets a flag on the dependent nodes to mark them as dirty, including the parents of the dependent nodes all the way down to the root. After each change we run an algorithm that is much like the algorithm for constructing the dependent graph from scratch, but it skips over any clean node and reconstructs each dirty node, keeping track of whether the reconstructed node is actually different from the dirty node. This can also get tricky.

We can represent the logical connection between the original graph and the dependent graph as a data structure, like a list of constraints, perhaps designed using a declarative language. When the original graph changes we need only scan the list to discover which constraints are violated and how the dependent tree needs to change to correct the violation, all encoded as data.

We can reconstruct the dependent graph from scratch as though there were no existing dependent graph, and then compare the existing graph and the new graph to discover how it has changed. I'm sure this is the easiest way because I know there are algorithms available for detecting differences, but they are all quite computationally expensive and in principle it seems unnecessary so I'm deliberately avoiding this option.

What is the right way to deal with these sorts of problems? Surely there must be a design pattern that makes this whole thing almost easy. It would be nice to have a good solution for every problem of this general description. Does this class of problem have a name?

Let me elaborate on the troubles that this problem causes. This issue pops up in various places, whenever two parts of a project operate on graphs, with each graph being a different representation of the same thing that changes while the software is running. It's like making an adapter for an interface, but instead of wrapping a single object or a fixed number of objects, we need to wrap an entire graph of arbitrary size.

Every time I try this I end up with a confusing unmaintainable mess. The control flow of observers can be difficult to follow when it gets complicated, and the algorithm for converting one graph to another is usually tricky enough to follow when its laid out plainly and not spread across multiple classes. The problem is that there seems to be no way to use just a plain, straight-forward graph conversion algorithm when the original graph is changing.

Naturally we can't just use an ordinary graph conversion algorithm directly because that can't respond to changes in any way other than starting from scratch, so what are the alternatives? Perhaps the algorithm could be written in a continuation-passing style where each step of the algorithm is represented as an object with a method for each type of node in the original graph, like a visitor. Then the algorithm can be assembled by composing various simple visitors together.

Another example: Suppose you have a GUI that is laid out like you might in Java Swing, using JPanels and layout managers. You can simplify that process by using nested JPanels in place of complex layout managers, so you end up with a tree of various containers that includes nodes that exist only for layout purposes and are otherwise meaningless. Now suppose that the same tree that is used to generate your GUI is also used in another part of your application, but instead of laying the tree out graphically it is working with a library that will generate an abstract representation tree as a system of folders. In order to use this library, we need to have a version of the tree that doesn't have the layout nodes; the layout nodes need to be flattened into their parent nodes, but the library still needs to be notified each time the tree changes as though the two versions of the tree were a single data structure.

Another way to look at it: The very concept of working with mutable trees violates the Law of Demeter. It wouldn't really be a violation of the law if the tree were a value as parse trees and syntax trees normally are, but in that case there would be no problem since nothing would need to be kept up-to-date. So then this problem exists as a direct result of violating the Law of Demeter, but how do you avoid that in general when your domain seems to be about manipulating trees or graphs?

The Composite pattern is a wonderful tool for turning a graph into a single object and obeying the Law of Demeter. Is it possible to use the Composite pattern to effectively turn one kind of tree into another? Can you make a Composite parse tree so that it acts like an abstract syntax tree and even a control flow graph? Is there a way to do it without violating the single responsibility principle? The Composite pattern tends to cause classes to absorb every responsibility that they touch, but perhaps it could be combined with the Strategy pattern somehow.

答:
I think your scenarios are discussing variations on the Observer Pattern. Each original node (“subject”) has (at least) the following two methods:

registerObserver(observer) – adds a dependent node to the list of observers.

notifyObservers() – calls x.notify(this) on each observer

And each dependent node (“observer”) has a notify(original) method. Comparing your scenarios:

The notify method immediately rebuilds a dependent subtree.

The notify method sets a flag, the recomputation happens after each set of updates.

The notifyObservers method is smart and only notifies those observers whose constraints are invalidated. This would probably use the Visitor Pattern, so that the dependent nodes can offer a method that decides this.

(this pattern has no relation to brute-force rebuilding)

As the first three ideas are just variations on the observer pattern, their design will have similar complexity (as it happens, they are actually ordered in increasing complexity – I'd think №1 is the most simple to implement).

I can think of one enhancement: building the dependent trees lazily. Each dependent node would then have a boolean flag that is either set to valid or invalid. Each accessor method would check this flag and, if necessary, recalculate the subtree. The difference to №2 is that recalculation happens on access, not upon change. This would probably result in fewest computations, but can lead to significant difficulties if the type of a node would have to change upon access.

I would also like to challenge the need for multiple dependent trees. For example, I always structure my parsers in a way that they immediately emit an AST. Information that is only relevant during construction of this tree doesn't have to be stored in any permanent data structure. Likewise, you can also choose your objects in such a way that the AST has an interpretation as a control flow graph.

For a real-life example, the compiler part inside the perl interpreter does this: The AST is built bottom-up, during which some nodes are constant-folded away. In a second run, the nodes are connected in execution order, during which some nodes are skipped by optimizations. The result is very fast parsing (and few allocations), but very limited optimizations. It should be noted that while such a design is possible, it is probably not something you should strive for: It is a calculated trade-off complete violation of the Single-Responsibility Principle.

If you do actually need multiple trees, then you should also consider whether they really have to be built simultaneously. In the majority of cases, a parse tree is constant after the parse. Likewise, an AST will probably stay constant after macros are resolved and AST-level optimizations have been executed.


问:
Is there a difference between iterable and enumerable?
Many languages seem to have structures that are very similar called iterable or enumerable. These are structures that can be iterated or enumerated over, which seem to me extremely similar things.  Are these words synonymous or is there a subtle semantic difference between iterable and enumerable which justifies the choice of term?</p>

答:
enumeration is counting,
iteration is a replaying

a second enumeration will yield the same number,
an iteration may be a variation

fractals are built by iterations of a function, repeating the function on the result of the last iteration,
each iteration has a different value


问:
Explanation needed, for “Ask, don't tell” approach?
I'm taking a course on design patterns in software engineering and here I'm trying to understand the good and the bad way of design relating to "coupling" and "cohesion".

I could not understand the concept described in the following image.

The example of code shown in the image is ambiguous to me, so I can't quite clearly get what exactly "Ask, don't tell!" approach mean. Could you please explain?

答:
The first example tells the object in question, "I need these accessors and this data from those accessors". That may be fine and good but it requires that you know how the object accesses those things.

The second example asks the object "Can you do this thing?", and then the object either returns that operation or fails. There is no requirement of internal knowledge of the object, thus facilitating the idea of loose coupling since I can then freely change the underlying object's interal functionality so long as the accessor interface, the "tum.addStudentToLecture(...), remains the same.


问:
Is Java easy decompilation a factor worth considering
We are considering the programming language for a desktop application with extended GUI use (tables, windows) and heavy database use.
We considered Java for use however the fact that it can be decompiled back very easily into source code is holding us back.

There are of course many obfuscators available however they are just that: obfuscators.
The only obfuscation worth doing we got was stripping function and variables names into meaningless letters and numbers so that at least stealing code and renaming it back into something meaningful is too much work and we are 100% sure it is not reversible back in any automated way.

However as it concerns to protecting internals (like password hashes or sensible variables content) we found obfuscators really lacking.

Is there any way to make Java applications as hard to decode as .exe counterparts?

And is it a factor to consider when deciding whether to develop in Java a desktop application?

答:
Java is relatively easy to decompile back into legal Java code and with the abundance of programs capable of doing so it should definitely be a deciding factor whether to make use of Java for desktop applications. Albeit true that obfuscators do a good job at making it hard to make sense of your code it should be considered that if the data you are trying protect to is valuable enough it can and will be found.

No matter what you write your application in there will always be the chance of your application being reverse engineered. For instance if you write your program in Assembly it will take some effort but it can still be reverse engineered into  compilable/understandable source. When choosing what language to write your application in you should consider how much effort it will take to reverse engineer you app with Java and C# being one of the easiest and C and Assembly being the hardest.

You can also attempt to hide sensitive data in the app/code by making use of the following techniques:

Encrypt variable data and have it decrypted at runtime.

Encrypt the entire executable section of your application and decrypt it at runtime using an unpacker (this is not the best option as it will result in AV software thinking your application is a virus)

Make sure buffers containing sensitive data are nulled after use.

Keeping sensitive data on a remote server and make use of SSL to download it at runtime.

I hope this answers your question.


问:
The clock problem - to if or not to if?
Let's say, we have a simple digital clock. To "power" it, we use a routine executed every second. We update seconds part in it. But, what about minutes and hours part?

What is better / more professional / offers better performance:

Ignore all checking and update hour, minute and seconds part each time, every second.

Use if + a variable for checking, if 60 (or 3600) seconds passed and update minute / hour part only at that precise moments.

This leads us to a question, what is better -- unnecessary drawings (first approach) or extra ifs?

I've just spotted a Javascript digital clock, one of millions similar on one of billions pages. And I noticed that all three parts (hours, minutes and seconds) are updated every second, though first changes its value only once per 3600 seconds and second once per 60 seconds.

I'm not to experienced developer, so I might me wrong. But everything, what I've learnt up until now, tells me, that if are far better then executing drawing / refreshing sequences only to draw the same content.

答:
Efficiency is important, but accuracy is even more important.  This is why a good JavaScript clock will do exactly what you're describing.

It works something like this:

```<code>function update_clock
  Update current time (completely)
  set a timer to come back 1 second later and call update_clock
</code>```

This may seem like overkill, but remember that the timers are not 100% accurate.  If it comes back 1.01 seconds later instead of 1 second later, your clock can start to drift, which means simply adding 1 to the seconds value isn't good enough.  Also, this way it can be done with only one timer, instead of needing two or three.

Also, let's say someone is viewing a webpage, and then they put the system to sleep for a few hours and start it back up.  If your clock script resynchronizes correctly every second, this won't cause any glitches; the clock will just resynchronize against the system clock.  Fancier attempts might well get screwed up by this.

Remember, correctness is almost always more important than efficiency, especially when it's not actually causing a performance bottleneck in your code.

Title: The clock problem - to if or not to if?

Body:
Efficiency is important, but accuracy is even more important.  This is why a good JavaScript clock will do exactly what you're describing.

It works something like this:

function update_clock
  Update current time (completely)
  set a timer to come back 1 second later and call update_clock

This may seem like overkill, but remember that the timers are not 100% accurate.  If it comes back 1.01 seconds later instead of 1 second later, your clock can start to drift, which means simply adding 1 to the seconds value isn't good enough.  Also, this way it can be done with only one timer, instead of needing two or three.

Also, let's say someone is viewing a webpage, and then they put the system to sleep for a few hours and start it back up.  If your clock script resynchronizes correctly every second, this won't cause any glitches; the clock will just resynchronize against the system clock.  Fancier attempts might well get screwed up by this.

Remember, correctness is almost always more important than efficiency, especially when it's not actually causing a performance bottleneck in your code.


答:
Consider drift, as Mason Wheeler mentioned. Do not increment each counter, rather update the clock state directly.

Do not assume that every minute has 60 seconds. Some have 59, others 61. If you do naive datetime math, you will also stumble over timezone and daylight saving time issues, or create new Y2K Y2038 bugs. Most languages have solid datetime libraries, use them instead to determine what time it actually is.

Updating three clock hands isn't necessarily significantly more expensive than updating one. If updates are expensive, one would usually draw to an off-screen buffer and update once (often, this technique also makes for smoother animations). Note: updating ≠ drawing.

Consider also that each update may cause a re-draw of the whole image. If the moved clock hand covered part of another, then the hand below will have to be re-drawn anyway. If multiple layers are composited over another, then your code may not realize this, but a redraw will still take place: the final image is (presumably) just a buffer of bytes.

All in all, I am vehemently opposed against trying to save a few cycles by taking the wrong shortcuts. Yes, a good programmer will try to write efficient code, but this is a wonderful example how premature optimization can be evil.

So if and only if it is valid to take the shortcut of only drawing updates when necessary, then by all means please do so. Otherwise, use the presumably inefficient variant (conjecture: it isn't that bad), or find other ways to optimize.

Title: The clock problem - to if or not to if?

Body:
Let's say, we have a simple digital clock. To "power" it, we use a routine executed every second. We update seconds part in it. But, what about minutes and hours part?

What is better / more professional / offers better performance:

Ignore all checking and update hour, minute and seconds part each time, every second.

Use if + a variable for checking, if 60 (or 3600) seconds passed and update minute / hour part only at that precise moments.

This leads us to a question, what is better -- unnecessary drawings (first approach) or extra ifs?

I've just spotted a Javascript digital clock, one of millions similar on one of billions pages. And I noticed that all three parts (hours, minutes and seconds) are updated every second, though first changes its value only once per 3600 seconds and second once per 60 seconds.

I'm not to experienced developer, so I might me wrong. But everything, what I've learnt up until now, tells me, that if are far better then executing drawing / refreshing sequences only to draw the same content.


答:
You will probably never have more than a couple hash types, so you can solve this without extending your database.

If the methods have different hash lengths, and each method's hash length are constant (say, transitioning from md5 to hmac-sha1), you can tell the method from the hash length. If they have the same length, you can calculate the hash using the new method first, then the old method if the first test failed.
If you have a field (not shown) telling when the user was last updated/created, you can use that as an indicator for which method to use.

Title: Updating password hashing without forcing a new password for existing users

Body:
You maintain an existing application with an established user base. Over time it is decided that the current password hashing technique is outdated and needs to be upgraded. Furthermore, for UX reasons, you don't want existing users to be forced to update their password. The whole password hashing update needs to happen behind the screen.

Assume a 'simplistic' database model for users that contains:

ID

Email

Password

How does one go around to solving such a requirement?

My current thoughts are:

create a new hashing method in the appropriate class

update the user table in the database to hold an additional password
field

Once a user successfully logs in using the outdated password hash, fill the second password field with the updated hash

This leaves me with the problem that I cannot reasonable differentiate between users who have and those who have not updated their password hash and thus will be forced to check both. This seems horribly flawed.

Furthermore this basically means that the old hashing technique could be forced to stay indefinitely until every single user has updated their password. Only at that moment could I start removing the old hashing check and remove the superfluous database field.

I'm mainly looking for some design tips here, since my current 'solution' is dirty, incomplete and what not, but if actual code is required to describe a possible solution, feel free to use any language.


问:
How accurate is "Business logic should be in a service, not in a model"?
Situation

Earlier this evening I gave an answer to a question on StackOverflow.

The question:

Editing of an existing object should be done in repository layer or in service?

For example if I have a User that has debt. I want to change his debt. Should I do it in UserRepository or in service for example BuyingService by getting an object, editing it and saving it ?

My answer:

You should leave the responsibility of mutating an object to that same object and use the repository to retrieve this object.

Example situation:

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}
```

<p><em>A comment I received:</em></p>

<blockquote>
  <p>Business logic should really be in a service. Not in a model.</p>
</blockquote>

<p><strong>What does the internet say?</strong></p>

<p>So, this got me searching since I've never really (consciously) used a service layer.
I started reading up on the Service Layer pattern and the Unit Of Work pattern but so far I can't say I'm convinced a service layer has to be used.</p>

<p>Take for example this article by Martin Fowler on the anti-pattern of an Anemic Domain Model:</p>

<blockquote>
  <p>There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters. Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. Instead there are a set of service objects which capture all the domain logic. These services live on top of the domain model and use the domain model for data.</p>

  <p>(...)  The logic that should be in a domain object is domain logic - validations, calculations, business rules - whatever you like to call it.</p>
</blockquote>

<p>To me, this seemed exactly what the situation was about: I advocated the manipulation of an object's data by introducing methods inside that class that do just that. However I realize that this should be a given either way, and it probably has more to do with how these methods are invoked (using a repository).</p>

<p>I also had the feeling that in that article (see below), a Service Layer is more considered as a façade that delegates work to the underlying model, than an actual work-intensive layer.</p>

<blockquote>
  <p>Application Layer [his name for Service Layer]: Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems. The tasks this layer is responsible for are meaningful to the business or necessary for interaction with the application layers of other systems. This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down. It does not have state reflecting the business situation, but it can have state that reflects the progress of a task for the user or the program.</p>
</blockquote>

<p>Which is reinforced here:</p>

<blockquote>
  <p>Service interfaces. Services expose a service interface to which all inbound messages are sent. You can think of a service interface as a façade that exposes the business logic implemented in the application (typically, logic in the business layer) to potential consumers.</p>
</blockquote>

<p>And here:</p>

<blockquote>
  <p>The service layer should be devoid of any application or business logic and should focus primarily on a few concerns. It should wrap Business Layer calls, translate your Domain in a common language that your clients can understand, and handle the communication medium between server and requesting client.</p>
</blockquote>

<p>This is a serious contrast to other resources that talk about the Service Layer:</p>

<blockquote>
  <p>The service layer should consist of classes with methods that are units of work with actions that belong in the same transaction.</p>
</blockquote>

<p>Or the second answer to a question I've already linked:</p>

<blockquote>
  <p>At some point, your application will want some business logic. Also, you might want to validate the input to make sure that there isn't something evil or nonperforming being requested. This logic belongs in your service layer.</p>
</blockquote>

<p><strong>"Solution"?</strong></p>

<p>Following the guidelines in this answer, I came up with the following approach that uses a Service Layer:</p>

<pre class="lang-cs prettyprint-override"><code>class UserController : Controller {
    private UserService _userService;

    public UserController(UserService userService){
        _userService = userService;
    }

    public ActionResult MakeHimPay(string username, int amount) {
        _userService.MakeHimPay(username, amount);
        return RedirectToAction("ShowUserOverview");
    }

    public ActionResult ShowUserOverview() {
        return View();
    }
}

class UserService {
    private IUserRepository _userRepository;

    public UserService(IUserRepository userRepository) {
        _userRepository = userRepository;
    }

    public void MakeHimPay(username, amount) {
        _userRepository.GetUserByName(username).makePayment(amount);
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}
</code>```

Conclusion

All together not much has changed here: code from the controller has moved to the service layer (which is a good thing, so there is an upside to this approach). However this doesn't look like it had anything to do with my original answer.

I realize design patterns are guidelines, not rules set in stone to be implemented whenever possible. Yet I have not found a definitive explanation of the service layer and how it should be regarded.

Is it a means to simply extract logic from the controller and put it inside a service instead?

Is it supposed to form a contract between the controller and the domain?

Should there be a layer between the domain and the service layer?

And, last but not least: following the original comment

Business logic should really be in a service. Not in a model.

Is this correct?

How would I introduce my business logic in a service instead of the model?

答:
How would you implement your business logic in the service layer? When you make a payment from a user, you a creating a payment, not just deducting a value from a property.

Your make payment method needs to create a payment record, add to that user's debt and persist all of this in your repositories. Doing this in a service method is incredibly straightforward, and you can also wrap the whole operation in a transaction. Doing the same in an aggregated domain model is much more problematic.

ContentLicense: CC BY-SA 4.0


问:
What exactly is bootstrap admin-template and how it is supposed to be used
So this is my second ASP.NET MVC 4 project. It's decided that for this one we will use this template and it was said in a way that I felt really stupid for not knowing how exactly this template will help us and what exactly we gain by using it.

I'm used to using HTML/CSS for the UI combined with jQuery. Now it seems that instead of jQuery we will be using bootstrap which as far as I understand is just another JS library created from twitter, so if that's it then this part is clear. What I really need to clarify for myself is what exactly this theme is used for, what is offering, why one would want to use such a theme? From what I see in the live demo maybe it's just a stack of premade controls that you can use in the front end along with bootstrap.js and maybe I'm just confused because on the page is shown as much as possible just for presentational purposes. If that's right, still I wonder where I can find info for the current theme, the controls that it offers and the functionality that I get and not least - how to use it.

But still those are just my assumptions. What I really need is a clarification on what exactly is this theme for, what is the advantage using it, is there a good tutorials about how to use such themes in the context of ASP.NET MVC 3+.

Also any additional info about this theme and generally on using themes in ASP.NET MVC will be much appreciated.

答:
Bootstrap is less of a javascript library and more of a CSS framework with some additional javascript widgets. There is nothing preventing you from using jQuery or some other javascript library of your choice (indeed, it may be required to get the functionality you need.)

The use case for Bootstrap is to get the product out the door without spending time worrying about how each control should look. It defines some standard styles for common elements/widgets and styles them to look good. It uses best practices and common sense to get a uniform look for everything.

There is absolutely nothing that is ASP.NET MVC specific about Bootstrap. It is pure front-end goodness, so it doesn't care in the slightest on how you render the HTML to start with. The entire purpose of Bootstrap is to bootstrap (get it?) your user interface.


答:
This is one of those things that really depends on the use case. The overall point of a service layer is to consolidate business logic together. This means that several controllers can call the same UserService.MakeHimPay() without actually caring about how the payment is done. What goes on in the service may be as simple as modifying an object property or it may be doing complex logic dealing with other services (i.e., calling out to third party services, calling validation logic, or even just simply saving something to the database.)

This doesn't mean you have to strip ALL logic from the domain objects. Sometimes it just makes more sense to have a method on the domain object do some calculations on itself. In your final example, the service is a redundant layer over the repository/domain object. It provides a nice buffer against requirements changes, but it really isn't necessary. If you think you need a service, try having that do the simple "modify property X on object Y" logic instead of the domain object. Logic on the domain classes tends to fall into the "calculate this value from fields" rather than exposing all fields via getters/setters.

Title: How accurate is "Business logic should be in a service, not in a model"?

Body:
Situation

Earlier this evening I gave an answer to a question on StackOverflow.

The question:

Editing of an existing object should be done in repository layer or in service?

For example if I have a User that has debt. I want to change his debt. Should I do it in UserRepository or in service for example BuyingService by getting an object, editing it and saving it ?

My answer:

You should leave the responsibility of mutating an object to that same object and use the repository to retrieve this object.

Example situation:

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}
```

<p><em>A comment I received:</em></p>

<blockquote>
  <p>Business logic should really be in a service. Not in a model.</p>
</blockquote>

<p><strong>What does the internet say?</strong></p>

<p>So, this got me searching since I've never really (consciously) used a service layer.
I started reading up on the Service Layer pattern and the Unit Of Work pattern but so far I can't say I'm convinced a service layer has to be used.</p>

<p>Take for example this article by Martin Fowler on the anti-pattern of an Anemic Domain Model:</p>

<blockquote>
  <p>There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters. Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. Instead there are a set of service objects which capture all the domain logic. These services live on top of the domain model and use the domain model for data.</p>

  <p>(...)  The logic that should be in a domain object is domain logic - validations, calculations, business rules - whatever you like to call it.</p>
</blockquote>

<p>To me, this seemed exactly what the situation was about: I advocated the manipulation of an object's data by introducing methods inside that class that do just that. However I realize that this should be a given either way, and it probably has more to do with how these methods are invoked (using a repository).</p>

<p>I also had the feeling that in that article (see below), a Service Layer is more considered as a façade that delegates work to the underlying model, than an actual work-intensive layer.</p>

<blockquote>
  <p>Application Layer [his name for Service Layer]: Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems. The tasks this layer is responsible for are meaningful to the business or necessary for interaction with the application layers of other systems. This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down. It does not have state reflecting the business situation, but it can have state that reflects the progress of a task for the user or the program.</p>
</blockquote>

<p>Which is reinforced here:</p>

<blockquote>
  <p>Service interfaces. Services expose a service interface to which all inbound messages are sent. You can think of a service interface as a façade that exposes the business logic implemented in the application (typically, logic in the business layer) to potential consumers.</p>
</blockquote>

<p>And here:</p>

<blockquote>
  <p>The service layer should be devoid of any application or business logic and should focus primarily on a few concerns. It should wrap Business Layer calls, translate your Domain in a common language that your clients can understand, and handle the communication medium between server and requesting client.</p>
</blockquote>

<p>This is a serious contrast to other resources that talk about the Service Layer:</p>

<blockquote>
  <p>The service layer should consist of classes with methods that are units of work with actions that belong in the same transaction.</p>
</blockquote>

<p>Or the second answer to a question I've already linked:</p>

<blockquote>
  <p>At some point, your application will want some business logic. Also, you might want to validate the input to make sure that there isn't something evil or nonperforming being requested. This logic belongs in your service layer.</p>
</blockquote>

<p><strong>"Solution"?</strong></p>

<p>Following the guidelines in this answer, I came up with the following approach that uses a Service Layer:</p>

<pre class="lang-cs prettyprint-override"><code>class UserController : Controller {
    private UserService _userService;

    public UserController(UserService userService){
        _userService = userService;
    }

    public ActionResult MakeHimPay(string username, int amount) {
        _userService.MakeHimPay(username, amount);
        return RedirectToAction("ShowUserOverview");
    }

    public ActionResult ShowUserOverview() {
        return View();
    }
}

class UserService {
    private IUserRepository _userRepository;

    public UserService(IUserRepository userRepository) {
        _userRepository = userRepository;
    }

    public void MakeHimPay(username, amount) {
        _userRepository.GetUserByName(username).makePayment(amount);
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}
</code>```

Conclusion

All together not much has changed here: code from the controller has moved to the service layer (which is a good thing, so there is an upside to this approach). However this doesn't look like it had anything to do with my original answer.

I realize design patterns are guidelines, not rules set in stone to be implemented whenever possible. Yet I have not found a definitive explanation of the service layer and how it should be regarded.

Is it a means to simply extract logic from the controller and put it inside a service instead?

Is it supposed to form a contract between the controller and the domain?

Should there be a layer between the domain and the service layer?

And, last but not least: following the original comment

Business logic should really be in a service. Not in a model.

Is this correct?

How would I introduce my business logic in a service instead of the model?


问:
Does C++ support subtyping?
I know it might be a silly question to ask, but I didn't quite get an a absolute clear answer on this matter, so I thought I'd put it here.

Does c++ support the subtyping in the sense that it fulfills Liskov's principle fully? I understand how parametric polymorphism, inclusion polymorphism(subclassing and overriding) work in c++ but I'm not entirely sure or understand if subtyping exists in the context of C++. Could you please explain?

答:
Does c++ support the subtyping in the sense that it fulfills Liskov's principle fully?

C++ is fully capable of supporting the Liskov Substitution Principle if the programmer uses it that way. Just like many other languages, it will not prevent you from doing something that violates the principle.

And yes, both "conventional" polymorphism achieved by inheritance and parameteric/static polymorphism provided by template shenanigans work as far as this question is concerned.

Title: Does C++ support subtyping?


答:
"Ask" code breaks when its object changes the details of its operation.  It has to state the types the object will be returning, it has to make assumptions about the mutability and synchronicity of those returns, and it forces other objects to implement "Ask" code to provide the other details they need to cooperate.

"Tell" code, by contrast, keeps all of types and implementation considerations in the hands of the object that can change them.  When they do change, external "Tell" code doesn't have to be revised in order to remain valid.

To make it concrete using your example, let's say that tomorrow, you or a co-worker:

Need to make the list of students accessible asynchronously and can't use a SortedList.

Need to store students by different keys in multiple containers, so student.getKey() becomes ambiguous or misleading.

Need to query the elements of pse2013students by more than a simple key.

If you used the "Ask" code, you need to revise both the tum object and the method that employs it in the example.  If you use the "Tell" code, you only needed to make changes to the tum object.  It doesn't look like much of a difference when your code base is two lines, but in a non-trivial program, it can become a severe maintainability hazard.

Title: Explanation needed, for “Ask, don't tell” approach?

Body:
I'm taking a course on design patterns in software engineering and here I'm trying to understand the good and the bad way of design relating to "coupling" and "cohesion".

I could not understand the concept described in the following image.

The example of code shown in the image is ambiguous to me, so I can't quite clearly get what exactly "Ask, don't tell!" approach mean. Could you please explain?


答:
```<code>doTick() {
    second++;
    if ( (second % 60) == 0 ) {
        minute++;
        second = 0;
        if ( (minute % 60) == 0 ) {
            hour++;
            minute = 0;
            if ( (hour % 24) == 0 ) {
                day++;
                hour = 0;
            }
        } // end 60 minute check
    } // end 60 second check
} // end doTick()
</code>```

No unnecessary checks or increments.

However, if you want accurate time use the JavaScript Date object (assuming you are using JavaScript).  As another commenter said, in the real world you generally can't rely on something calling your function exactly every second.

Title: The clock problem - to if or not to if?

Body:
doTick() {
    second++;
    if ( (second % 60) == 0 ) {
        minute++;
        second = 0;
        if ( (minute % 60) == 0 ) {
            hour++;
            minute = 0;
            if ( (hour % 24) == 0 ) {
                day++;
                hour = 0;
            }
        } // end 60 minute check
    } // end 60 second check
} // end doTick()

No unnecessary checks or increments.

However, if you want accurate time use the JavaScript Date object (assuming you are using JavaScript).  As another commenter said, in the real world you generally can't rely on something calling your function exactly every second.


问:
Is there really anything to gain with complex design?
I've been working for a consulting firm for some time, with clients of various sizes, and I've seen web applications ranging in complexity from really simple:

MVC

Service Layer

EF

DB

To really complex:

MVC

UoW

DI / IoC

Repository

Service

UI Tests

Unit Tests

Integration Tests

But on both ends of the spectrum, the quality requirements are about the same.  In simple projects, new devs / consultants can hop on, make changes, and contribute immediately, without having to wade through 6 layers of abstraction to understand what's going on, or risking misunderstanding some complex abstraction and costing down the line.

In all cases, there was never a need to actually make code swappable or reusable - and the tests were never actually maintained past the first iteration because requirements changed, it was too time-consuming, deadlines, business pressure, etc etc.

So if - in the end -

testing and interfaces aren't used

rapid development (read: cost-savings) is a priority

the project's requirements will be changing a lot while in development

...would it be wrong to recommend a super-simple architecture, even to solve a complex problem, for an enterprise client?  Is it complexity that defines enterprise solutions, or is it the reliability, # concurrent users, ease-of-maintenance, or all of the above?

I know this is a very vague question, and any answer wouldn't apply to all cases, but I'm interested in hearing from devs / consultants that have been in the business for a while and that have worked with these varying degrees of complexity, to hear if the cool-but-expensive abstractions are worth the overall cost, at least while the project is in development.

答:
To Architect, Or Not To Architect

To rephrase Einstein, "things should be as simple as possible - but no simpler." It's important to understand the true use of some architectures - and they aren't necessarily for individual performance, and often not  for job satisfaction either.

Sometimes architectures are so complicated because an enterprise project is just so large, with so many people at work, that the architecture is largely to allow so many people to work towards something without everyone tripping over everyone else. They are, at times, little more than complexity added that reduces individual productivity and makes work harder - but permits large numbers of people to work. This works when the added effort outweighs the individually decreased will to live, err, I mean "productivity".

Is this your client's situation? Well, if their budget isn't in the millions for this project, maybe not. If it's under a 100k, then almost certainly not. You build a concrete bunker for a nuclear reactor, not a wood burning stove :)

It is not necessarily wrong to suggest "the simplest thing that could possibly work" for your client, if that's what the situation calls for. It might be the best possible way to handle it. The easiest way to see is compare it to commercially available/open source projects that are designed to accomplish a similar task (this is your due diligence market research, anyway), and see what it took them to do what they did.

Of course, when you are working with millions of dollars you should be aware of some perverse incentives in play. In short, "ass covering": if you recommend a super complex architecture system that requires a PhD to understand properly, when it goes to hell who's fault was it? Not yours, of course - you suggested only the finest in sophisticated technologies that everyone says is the best - but they are "complicated" and "difficult", so the blame is with the people who tried to implement it. They must have just not been smart enough or skilled enough...in other words, lots of advice is given to ensure you don't look bad when projects fail, which they inevitably must as not all projects are successful. It's bad juju, but it is a fact of our reality.

Failure To Follow Through

I would suggest that failure to continually update tests and follow-through on architecture decisions (tossing plans when they change instead of updating them, etc) is why so many systems end up being thrown out and rewritten from scratch or wholesale replaced with a new 'solution' a few years down the road.

When things that enforce clarity and consistency are thrown out for expedience, it is easy to sometimes think you were very sly and are really "Getting Things Done" when in fact you made future changes harder and more complicated; it is very common to steal from future productivity for immediate gains. Its bad specifically when no one realizes that's what's happening.

Testing, for instance, is specifically best suited to when things change. You change the tests to reflect what the new direction is, and then go about fixing all the stuff that is now "broken" because people changed their minds or came to a realization that they missed something last time. This is like giving up sleeping because you have a lot to get done this week - its going to make things harder.

In Conclusion, "It Depends" (Helpful, Isn't It?)

Architectural complexity is an overhead cost, like renting a larger space for a brick-n-mortar business; it only makes sense when there is real complexity that needs to be managed. If it's a team of 3 working on a solution that is relatively conventional, simple MVC and minimal tooling is probably entirely sufficient.

If it's a complex, multi-subsystem, enterprise software solution, with millions on budget and at least a half-dozen teams of 3-5? You're going to be begging for the sweet, sweet love that only round-trip engineering on object oriented program analysis and all its charts and diagrams and models can give. Anything to help you keep the dozens or hundreds of sets of eyes from unblinkingly staring at you, wondering what they are supposed to do today and how they are supposed to get anything done at all.


答: I would say that if you are developing applications for the enterprise then you or someone in charge of your projects (Proj mgr) should have a better feel for the amount of work that should go in to the projects. If you are seeing a waste of time then you should discuss your view with the Proj mgr. The way I feel and operate is always on a per basis type of judgement, but I always look out for that client that will throw you a curve ball. I would error to doing a good job by dotting your I's and crossing your t's. I would also make sure that I have the proper application lifecycle management in place so that most of the overhead is automated so that it ill save time etc... I hope that helps!

Title: Is there really anything to gain with complex design?

Body:
I've been working for a consulting firm for some time, with clients of various sizes, and I've seen web applications ranging in complexity from really simple:

MVC

Service Layer

EF

DB

To really complex:

MVC

UoW

DI / IoC

Repository

Service

UI Tests

Unit Tests

Integration Tests

But on both ends of the spectrum, the quality requirements are about the same.  In simple projects, new devs / consultants can hop on, make changes, and contribute immediately, without having to wade through 6 layers of abstraction to understand what's going on, or risking misunderstanding some complex abstraction and costing down the line.

In all cases, there was never a need to actually make code swappable or reusable - and the tests were never actually maintained past the first iteration because requirements changed, it was too time-consuming, deadlines, business pressure, etc etc.

So if - in the end -

testing and interfaces aren't used

rapid development (read: cost-savings) is a priority

the project's requirements will be changing a lot while in development

...would it be wrong to recommend a super-simple architecture, even to solve a complex problem, for an enterprise client?  Is it complexity that defines enterprise solutions, or is it the reliability, # concurrent users, ease-of-maintenance, or all of the above?

I know this is a very vague question, and any answer wouldn't apply to all cases, but I'm interested in hearing from devs / consultants that have been in the business for a while and that have worked with these varying degrees of complexity, to hear if the cool-but-expensive abstractions are worth the overall cost, at least while the project is in development.


问:
When are Getters and Setters Justified?
Getters and setters are often criticized as being not proper OO. On the other hand, most OO code I've seen has extensive getters and setters.

When are getters and setters justified? Do you try to avoid using them? Are they overused in general?

If your favorite language has properties (mine does) then such things are also considered getters and setters for this question. They are the same thing from an OO methodology perspective. They just have nicer syntax.

Sources for Getter/Setter Criticism (some taken from comments to give them better visibility):

http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html

http://typicalprogrammer.com/?p=23

http://c2.com/cgi/wiki?AccessorsAreEvil

http://www.darronschall.com/weblog/2005/03/no-brain-getter-and-setters.cfm

http://www.adam-bien.com/roller/abien/entry/encapsulation_violation_with_getters_and

http://www.yegor256.com/2014/09/16/getters-and-setters-are-evil.html

To state the criticism simply: Getters and Setters allow you to manipulate the internal state of objects from outside of the object. This violates encapsulation. Only the object itself should care about its internal state.

And an example

Procedural version of code:

```<code>struct Fridge
{
    int cheese;
}

void go_shopping(Fridge fridge)
{
     fridge.cheese += 5;
}
</code>```

Mutator version of code:

```<code>class Fridge
{
     int cheese;

     void set_cheese(int _cheese) { cheese = _cheese; }
     int get_cheese() { return cheese; }
 }

void go_shopping(Fridge fridge)
{
     fridge.set_cheese(fridge.get_cheese() + 5);
}
</code>```

The getters and setters made the code much more complicated without affording proper encapsulation. Because the internal state is accessible to other objects we don't gain a whole lot by adding these getters and setters.

The question has been previously discussed on Stack Overflow:

https://stackoverflow.com/questions/565095/java-are-getters-and-setters-evil

https://stackoverflow.com/questions/996179

答:
The basic reason for getters and setters in Java is very simple:

You can only specify methods, not fields, in an interface.

Hence, if you want to allow a field to pass across the interface, you will need a reader and a writer method.  These are traditionally called getX and setX for the field x.

Title: When are Getters and Setters Justified?


问:
Complex knowledge management system with CRM..written internally
We've all heard of salesforce and sugarcrm and the likes of systems like this.
Unfortunately at my workplace we have been asked to write a similiar system (rather then license or purchase).  Basically the database is fairly large.  Think of modules such as:
Corporate groups, customers, programs, projects, sub projects, and issue management.  In simple terms a corporate group has one to many customers.  A program has one or more projects.  A project has one or more sub projects.  And an issue can be created on many sub projects.

Of course the system is a bit more complex but instead of listing every single module I think its best to keep it simple.  In any event, the system in its current state has only two resources to be working on it (basically we have to do it all: CSS, database, jquery, asp.net and C#).  We've started off well by defining the UI master and footer pages that way we can reuse those across all of our pages.

Now comes the hard part.  The system will have about 4k end users with say 5-10% being concurrent users.  We are wondering if it makes sense to cache our database data (For say 5-10 minutes) rather then continously hit our database.  The reason being is some of these pages may have 5-10 search filters associated with the page.  Imagine every time a selection is made from a search box how many database hits.  Also some of these search fields cascade so selecting for instance an initial drop down may cascade several drop down boxes under them.

Is it wrong to cache because I am not finding too many articles on whether it is a good idea or not.  Remember the system is similiar to say a CRM system where we manage our various customers, projects, sub projects, issues, etc.

答:
Caching of some types can make sense, but 500 concurrent users is generally vastly below the point where you'd need to even consider it. 1-2 enterprise quality servers can handle thousands of concurrent users, even with pretty heavy usage, if sanely implemented.

It's good to perform capacity planning (here's a Link Server example), but database caching is likely to be optimization step 5 (at the earliest), with application-level caching being something more like step 10 - taken if you are still unable to keep up with demand, which given <1000 concurrent numbers should never happen. Unless you are handed some really, really under-powered server equipment, it shouldn't be anything you need to worry about.

Further, there are many kinds of caching, and with all the wonderful tools available manually caching data in the application - especially on a data-driven application like CRM - is probably the least helpful kind. Go with the ones you can just "turn on" and tweak first, when you find a need.

When and if a performance problem appears, profile to determine the source of the troubles, and adjust in the way that least impacts overall development.

As to the basic issue of caching, when its needed it can be the bees knees. In the simplest way, most modern database systems have easily implemented (or automatic) query caching, which can be a great way to lighten server load - especially if you have some fancy, complex queries and hundreds of thousands of records (or more).

More aggressive caching can be...challenging and time consuming, if you aren't already a DBWizard.


答:
If you care enough about rolling out the new hashing scheme to all users as quickly as possible (e.g. because the old one is really insecure), there is actually a way for instantaneous "migration" of every password.

The idea is basically to hash the hash. Rather than waiting for users provide their existing password (p) upon next login, you immediately use the new hashing algorithm (H2) on the existing hash already produced by the old algorithm (H1):

```<code>hash = H2(hash)  # where hash was previously equal to H1(p)
</code>```

After doing that conversion, you are still perfectly able to perform password verification; you just need to compute H2(H1(p')) instead of the previous H1(p') whenever user tries to log in with password p'.

In theory, this technique could be applied to multiple migrations (H3, H4, etc.). In practice, you would want to get rid of the old hash function, both for performance and readability reasons. Fortunately, this is quite easy: upon the next successful login, simply compute the new hash of user's password and replace the existing hash-of-a-hash with it:

```<code>hash = H2(p)
</code>```

You will also need additional column to remember what hash you're storing: the one of the password or of the the old hash. In the unfortunate event of database leak, this column shouldn't make the cracker's job any easier; regardless of its value, the attacker would still have to reverse the secure H2 algorithm rather than the old H1.

Body:
If you care enough about rolling out the new hashing scheme to all users as quickly as possible (e.g. because the old one is really insecure), there is actually a way for instantaneous "migration" of every password.

The idea is basically to hash the hash. Rather than waiting for users provide their existing password (p) upon next login, you immediately use the new hashing algorithm (H2) on the existing hash already produced by the old algorithm (H1):

hash = H2(hash)  # where hash was previously equal to H1(p)

After doing that conversion, you are still perfectly able to perform password verification; you just need to compute H2(H1(p')) instead of the previous H1(p') whenever user tries to log in with password p'.

In theory, this technique could be applied to multiple migrations (H3, H4, etc.). In practice, you would want to get rid of the old hash function, both for performance and readability reasons. Fortunately, this is quite easy: upon the next successful login, simply compute the new hash of user's password and replace the existing hash-of-a-hash with it:

hash = H2(p)

You will also need additional column to remember what hash you're storing: the one of the password or of the the old hash. In the unfortunate event of database leak, this column shouldn't make the cracker's job any easier; regardless of its value, the attacker would still have to reverse the secure H2 algorithm rather than the old H1.


问:
How to develop an app for a smartphone to access a web app?
My colleague developed an internal web application. This app works only in Internet Explorer, which means that I can't access it from my smartphone.

Is there any way to develop an application which will serve as a bridge between my smartphone and this web app, enabling me to use the web app from any other browser/mobile device?

答:
Nope.

You are attempting to find a technical solution to a human problem.

What you should do is to make pressure on your colleague to modify the web application to be W3C compliant and work with normal browsers.

Searching for workarounds would only make the problem grow: the web app would remain unusable outside IE, while growing over time, constantly hurting your company.

What if one day your company hires a person with a disability who can't use the app through IE?

What if Microsoft releases a version of IE which will break the compatibility with your app?

What if the person currently developing the web app leaves the company? Who would enjoy maintaining a web app which doesn't even care being compatible with any browser?

You (your company) lock yourself in a proprietary solution, and the worst one available on the market of browsers.

This is a mistake made by many companies a decade ago. The consequences were that those companies were not able to upgrade from IE 6 to anything else, and so would force their employees to use exclusively IE 6, forbidding any other browser.


答:
I can relate to your doubts regarding complex software development techniques, and would guess that there are a lot of people that can, for exactly the reasons you named: They add an overhead to the initial creation of a new system while not always instantly showing their benefits.

That does clearly not mean they do not exist, for every concept there is a reason, most of the times a good one. In total they should reduce the work needed to finalize a project and enhance it afterwards.

In theory, of course, and I would bet you learned all those theoretical benefits and now more than ever you see them fail. And that may have a good reason, too, using a concept right is not as easy as understanding why it is used, and while you may have the experience it takes to decide when to abstract and when not, your clients may not yet.

Using a concept at every possible point in your project can cost you a lot of time (see Telatsyns answer for a neat simple sentence on that) and even using a concept at the right place can cost you, if you are not experienced enough using it. As you said, those are no simple concepts but sometimes really complex ones that need to be fitted to your situation, a theoretical understanding can not be enough to use it fast and right.

And for those reasons it is of no surprise when your clients without really noticing drift away from the concepts and abandon their tests and abstractions and start working simple again.

Regarding the big barrier that software engineering can be, I suggest this article to you: The Seven Stages of Expertise in Software Engineering I stumbled over it somewhere on this page and it expresses some really interesting thoughts and experiences.


答:
In object oriented design, classes have a:

a public interface that does not change

hidden implementation that may be changed

So if you change the implementation, for example add new functionality, as long as the interface still works the way it did before, you can be assured that all dependent classes will continue to function properly and you don't need to test them.

So in the "bad" example, when the code "tells" the tum object how to add a student to the list. Now the invoking classes is messing around with the internals of how the student list is kept. If the author of the tum object decides to replace:

```<code>getStudentList(Lectures.PSE,2013)
</code>```

with a new function

```<code>getStudentMap(Lectures.PSE, Campus.Main, 2013)
</code>```

you have to change your code to get it to work the way it did before because of something they did. Upgrading common utility library would potentially become a nightmare be it might break tons of code. Yet the utility library might have some critical security fix so you might have to upgrade it.

In the good "ask" example, the code invokes a function inside the tum object to add a student to the list. The author of the tum object is maintaining this functionality and it is their responsibility not yours. This is a good thing. They are now obliged to keep it working correctly and if it doesn't now they are obliged to fix it, not you.

In addition, there might be other requirements you are not aware of that they might be doing. For example, checking the student records and if this is the very first lecture a student attends, mail them a welcome letter. Your class would have no idea about that (or care) and yet now if that became a requirement you would have to add and maintain that to your code.

Body:
In object oriented design, classes have a:

a public interface that does not change

hidden implementation that may be changed

So if you change the implementation, for example add new functionality, as long as the interface still works the way it did before, you can be assured that all dependent classes will continue to function properly and you don't need to test them.

So in the "bad" example, when the code "tells" the tum object how to add a student to the list. Now the invoking classes is messing around with the internals of how the student list is kept. If the author of the tum object decides to replace:

getStudentList(Lectures.PSE,2013)

with a new function

getStudentMap(Lectures.PSE, Campus.Main, 2013)

you have to change your code to get it to work the way it did before because of something they did. Upgrading common utility library would potentially become a nightmare be it might break tons of code. Yet the utility library might have some critical security fix so you might have to upgrade it.

In the good "ask" example, the code invokes a function inside the tum object to add a student to the list. The author of the tum object is maintaining this functionality and it is their responsibility not yours. This is a good thing. They are now obliged to keep it working correctly and if it doesn't now they are obliged to fix it, not you.

In addition, there might be other requirements you are not aware of that they might be doing. For example, checking the student records and if this is the very first lecture a student attends, mail them a welcome letter. Your class would have no idea about that (or care) and yet now if that became a requirement you would have to add and maintain that to your code.


答:
"Tell, don't ask" works on the premise that an object shouldn't have to be told to do something according to some information about the object itself. Surely the object should know its own state? You shouldn't have to couple code outside of the object to perform some function it could very well do itself. I found the example picture terribly confusing so I'll use another example instead.

Imagine you play a complex game such as World of Warcraft. You are a warlock and you want to use the Fear spell on some other player. The spell should send them running for 8 seconds. If you cast it again that time will be halved due to diminishing returns, and so on. There are many factors deciding if the spell hit should be a success or not.

Now, the Fear spell could be implemented like this:

```<code>function castFear(Player player) {
  if (player->isAPaladinAndFearsNothing())
    return false;
  if (player->hasTakenAntiFearPotion())
    return false;
  if (currentPlayer->getStat("shadow_magic_power") < player->getStat("shadow_magic_resistance"))
    return false;

  player->receiveFear();
}
</code>```

With "tell, don't ask" this code could be simplified drastically:

```<code>function castFear(Player player) {
  player->receiveFear(currentPlayer);
}
</code>```

The Player class could be implemented like this:

```<code>class Player {
  public boolean receiveFear(Player castingPlayer) {
    if (this->isAPaladinAndFearsNothing())
      return false;
    if (this->hasTakenAntiFearPotion())
      return false;
    if (castingPlayer->getStat("shadow_magic_power") < this->getStat("shadow_magic_resistance"))
      return false;

    // Get feared
  }
}
</code>```

Now, both solutions might seem quite similar, but if you think about it, whose responsibility is it to know if the target player can be feared or not? "Tell, don't ask" might appear as a "neat trick", but I've found this style of coding to be one of the cornerstones of OOP. You should not know of whatever complexity is hidden behind that public function and as such should not take action against it either. What if some of your new spells should also Fear your target? You'd have to stay up to date on all the checks you'd have to make, everywhere. If you wanted to implement "Healing Horror" that fears your target and heals you, you could just write:

```<code>function castHealingHorror(Player player) {
  currentPlayer->health += 50;
  player->receiveFear(currentPlayer);
}
</code>```

I'd say this is also a question of which object should perform the checks, the sender or the receiver? Well, think about it. If you were to send a letter to an official containing inappropriate wording, wouldn't your letter be halted somewhere along the way? For all you know someone might read the mail before your recipient does and filter it out as a security measure. Should you code for this as the sender? All you should do is take your prepared Letter object, give it to the mailman and that's it. Maybe it doesn't even reach the destination post office due to some inconvenience.

Expose yourself to as little complexity and information as possible and let each component deal with its own business rules. It's then easier to combine them into a fully encapsulated system.

Body:
"Tell, don't ask" works on the premise that an object shouldn't have to be told to do something according to some information about the object itself. Surely the object should know its own state? You shouldn't have to couple code outside of the object to perform some function it could very well do itself. I found the example picture terribly confusing so I'll use another example instead.

Imagine you play a complex game such as World of Warcraft. You are a warlock and you want to use the Fear spell on some other player. The spell should send them running for 8 seconds. If you cast it again that time will be halved due to diminishing returns, and so on. There are many factors deciding if the spell hit should be a success or not.

Now, the Fear spell could be implemented like this:

function castFear(Player player) {
  if (player->isAPaladinAndFearsNothing())
    return false;
  if (player->hasTakenAntiFearPotion())
    return false;
  if (currentPlayer->getStat("shadow_magic_power") < player->getStat("shadow_magic_resistance"))
    return false;

  player->receiveFear();
}

With "tell, don't ask" this code could be simplified drastically:

function castFear(Player player) {
  player->receiveFear(currentPlayer);
}

The Player class could be implemented like this:

class Player {
  public boolean receiveFear(Player castingPlayer) {
    if (this->isAPaladinAndFearsNothing())
      return false;
    if (this->hasTakenAntiFearPotion())
      return false;
    if (castingPlayer->getStat("shadow_magic_power") < this->getStat("shadow_magic_resistance"))
      return false;

    // Get feared
  }
}

Now, both solutions might seem quite similar, but if you think about it, whose responsibility is it to know if the target player can be feared or not? "Tell, don't ask" might appear as a "neat trick", but I've found this style of coding to be one of the cornerstones of OOP. You should not know of whatever complexity is hidden behind that public function and as such should not take action against it either. What if some of your new spells should also Fear your target? You'd have to stay up to date on all the checks you'd have to make, everywhere. If you wanted to implement "Healing Horror" that fears your target and heals you, you could just write:

function castHealingHorror(Player player) {
  currentPlayer->health += 50;
  player->receiveFear(currentPlayer);
}

I'd say this is also a question of which object should perform the checks, the sender or the receiver? Well, think about it. If you were to send a letter to an official containing inappropriate wording, wouldn't your letter be halted somewhere along the way? For all you know someone might read the mail before your recipient does and filter it out as a security measure. Should you code for this as the sender? All you should do is take your prepared Letter object, give it to the mailman and that's it. Maybe it doesn't even reach the destination post office due to some inconvenience.

Expose yourself to as little complexity and information as possible and let each component deal with its own business rules. It's then easier to combine them into a fully encapsulated system.


问:
Is throwing an error in unpredictable subclass-specific circumstances a violation of LSP?
Let's say I wanted to create a Java List<String> (see spec) implementation that uses a complex subsystem, such as a database or file system, for its store so that it acts as a persistent collection rather than an in-memory one.

So here's a skeleton implementation:

```<code>class DbBackedList implements List<String> {
  private DbBackedList() {}
  /** Returns a list, possibly non-empty */
  public static getList() { return new DbBackedList(); }
  public String get(int index) {
    return Db.getTable().getRow(i).asString();  // may throw DbExceptions!
  }
  // add(String), add(int, String), etc. ...
}
</code>```

My problem lies with the fact that the underlying DB API may encounter connection errors that are not specified in the List interface that it should throw.

My problem is whether this violates Liskov's Substitution Principle (LSP).

In his paper on LSP, Bob Martin actually gives an example of a PersistentSet that violates LSP. The difference is that his newly-specified Exception there is determined by the inserted value and so is strengthening the precondition. In my case the connection/read error is unpredictable and due to external factors and so is not technically a new precondition, merely an error of circumstance, perhaps like OutOfMemoryError which can occur even when unspecified.

In normal circumstances, the new Error/Exception might never be thrown. (The caller could catch if it is aware of the possibility, just as a memory-restricted Java program might specifically catch OOME.)

Is this therefore a valid argument for throwing an extra error and can I still claim to be a valid java.util.List (or pick your SDK/language/collection in general) and not in violation of LSP?

Edit: This argument might be more palatable if you consider a FileBackedList (more reliable "connection") rather than a DbBackedList.

If this does indeed violate LSP and thus not practically usable, I have provided two less-palatable alternative solutions as answers that you can comment on, see below.

Footnote: Use Cases

In the simplest case, the goal is to provide a familiar interface for cases when (say) a database is just being used as a persistent list, and allow regular List operations such as search, subList and iteration.

Another, more adventurous, use-case is as a slot-in replacement for libraries that work with basic Lists, e.g if we have a third-party task queue that usually works with a plain List:

new TaskWorkQueue(new ArrayList<String>()).start() which is susceptible to losing all it's queue in event of a crash, if we just replace this with:

new TaskWorkQueue(new DbBackedList()).start() we get a instant persistence and the ability to share the tasks amongst more than one machine.

In either case, we could either handle connection/read exceptions that are thrown, perhaps  retrying the connection/read first, or allow them to throw and crash the program (e.g. if we can't change the TaskWorkQueue code).

答:
If LSP is unquestionably being violated, I could instead introduced a Option Type class that the List nominally stores and returns, which encapsulates the return types and any errors in retrieval.

```<code>/**
 * Wraps a String for writing or reading from a database.
 */
interface DbString {
  public DbString(String str) { /* ... */ }
  /** @returns the String, or "" if hasError() returns true */
  public String() getString();
  /** @returns true if there was an error in retrieving the string */
  public boolean hasError();
}

/**
 * A list of DbStrings
 */
class DbBackedList implements List<DbString> {
  // .. as before

  public DbString get(int index) {
    return Db.getConnection.getTable().getRow(i).asString();  // may throw!
  }

  // add(DbString), add(int, DbString), etc. ...
}
</code>```

Usage is similar to regular lists.

```<code>List<String> l = new DbBackedList();
l.add(new DbString("foo"));
assertFalse(a.get(0).hasError());
assertEquals("foo", a.get(0).getString());
</code>```

At this point, though, it's arguably easier to create a new interface from scratch and not retrofit an existing one, however we lose some of the apparent familiarity with the List interface. If we want to provide other collections, such as Set or Map we will then have to create new interfaces for each of them.

Body:
If LSP is unquestionably being violated, I could instead introduced a Option Type class that the List nominally stores and returns, which encapsulates the return types and any errors in retrieval.

/**
 * Wraps a String for writing or reading from a database.
 */
interface DbString {
  public DbString(String str) { /* ... */ }
  /** @returns the String, or "" if hasError() returns true */
  public String() getString();
  /** @returns true if there was an error in retrieving the string */
  public boolean hasError();
}

/**
 * A list of DbStrings
 */
class DbBackedList implements List<DbString> {
  // .. as before

  public DbString get(int index) {
    return Db.getConnection.getTable().getRow(i).asString();  // may throw!
  }

  // add(DbString), add(int, DbString), etc. ...
}

Usage is similar to regular lists.

List<String> l = new DbBackedList();
l.add(new DbString("foo"));
assertFalse(a.get(0).hasError());
assertEquals("foo", a.get(0).getString());

At this point, though, it's arguably easier to create a new interface from scratch and not retrofit an existing one, however we lose some of the apparent familiarity with the List interface. If we want to provide other collections, such as Set or Map we will then have to create new interfaces for each of them.


问:
Automatically delete files after they expire
I've got this idea for some time and I was wondering if anyone has seen such a feature/app in any operating system and if you haven't, what do you think about it. Where do you think I should begin?

The idea is simple. I think we all have those files that are made and probably used for a few days and then are left on our disk and we never delete them or even check to see if we need them again. It'd be cool if you could right click on a file and click on "Expire in.. 3 days" for example. And the file gets deleted after 3 days. I have a great need for this and maybe some people will find it useful.

I was thinking of writing a script and use the Nautilus Action project in GNOME for a start.

答:
I've set up my webserver with a directory specifically for files which I'm offering for download for a limited time.

crontab:

```<code>@daily /path-to-script/autoexpire.pl >/dev/null 2>&1
</code>```

autoexpire.pl looks into that directory for files with the pattern *_expYYYY-MM-DD.* (such as file-for-Joe_exp2013-11-30.doc). Any files named explicitly with such an expiry date in the filename will be deleted once the expiry date is in the past.

```<code>#!/usr/bin/perl -w
use strict;

my $expdir="/path-to-my-static-webpages/htdocs/autoexpire";
my $today=`date +%Y-%m-%d`; chomp $today; # get date (human readable)
my $t=$today;
$t=~s/-//g; # make date numeric for comparison

chdir($expdir) or die "$!";
my @files = glob("*_exp*");

foreach my $file (@files){
        next unless($file=~/\W/);
        if($file=~/_exp(\d\d\d\d-\d\d-\d\d)\./){
                my $f=$1;
                $f=~s/-//g; # make expiry numeric for comparison
                print "checking $file against $today ... ";
                if($f < $t){
                        print "$f < $t. unlinking.\n";
                        unlink("$expdir/$file");
                }else{
                        print "$f !< $t. ignoring.\n"
                }
        }
}
</code>```

Body:
I've set up my webserver with a directory specifically for files which I'm offering for download for a limited time.

crontab:

@daily /path-to-script/autoexpire.pl >/dev/null 2>&1

autoexpire.pl looks into that directory for files with the pattern *_expYYYY-MM-DD.* (such as file-for-Joe_exp2013-11-30.doc). Any files named explicitly with such an expiry date in the filename will be deleted once the expiry date is in the past.

#!/usr/bin/perl -w
use strict;

my $expdir="/path-to-my-static-webpages/htdocs/autoexpire";
my $today=`date +%Y-%m-%d`; chomp $today; # get date (human readable)
my $t=$today;
$t=~s/-//g; # make date numeric for comparison

chdir($expdir) or die "$!";
my @files = glob("*_exp*");

foreach my $file (@files){
        next unless($file=~/\W/);
        if($file=~/_exp(\d\d\d\d-\d\d-\d\d)\./){
                my $f=$1;
                $f=~s/-//g; # make expiry numeric for comparison
                print "checking $file against $today ... ";
                if($f < $t){
                        print "$f < $t. unlinking.\n";
                        unlink("$expdir/$file");
                }else{
                        print "$f !< $t. ignoring.\n"
                }
        }
}


答:
The reason why his example is a violation of LSP is not because of the exception per se, it is the reason for the exception -- it is changing the contract.

A simpler, but more contrived example -- you have a List of ints, you decide you want to use it for a list of elementary grades completed, with a check to make sure that the numbers are within the required range, so you subclass ListInt as ListIntElementary.  ListIntElementary violates LSP.

You, on the other hand, have real world constraints that wouldn't apply to the base class, but your subclass can algorithmically be used anywhere the base class can, it accepts all acceptable inputs, returns only acceptable values.  Exceptions are neither input nor output in the LSP sense.

A new exception or new cause for an old exception (if you can find one that maps cleanly) is an implementation detail, not a violation of LSP.  It may mean that in practice that it is unsuitable as a replacement for the base class, but in theory once created, it can be used everywhere that the base class can be used.

In short, this is fine.

Title: Is throwing an error in unpredictable subclass-specific circumstances a violation of LSP?

Body:
Let's say I wanted to create a Java List<String> (see spec) implementation that uses a complex subsystem, such as a database or file system, for its store so that it acts as a persistent collection rather than an in-memory one.

So here's a skeleton implementation:

```<code>class DbBackedList implements List<String> {
  private DbBackedList() {}
  /** Returns a list, possibly non-empty */
  public static getList() { return new DbBackedList(); }
  public String get(int index) {
    return Db.getTable().getRow(i).asString();  // may throw DbExceptions!
  }
  // add(String), add(int, String), etc. ...
}
</code>```

My problem lies with the fact that the underlying DB API may encounter connection errors that are not specified in the List interface that it should throw.

My problem is whether this violates Liskov's Substitution Principle (LSP).

In his paper on LSP, Bob Martin actually gives an example of a PersistentSet that violates LSP. The difference is that his newly-specified Exception there is determined by the inserted value and so is strengthening the precondition. In my case the connection/read error is unpredictable and due to external factors and so is not technically a new precondition, merely an error of circumstance, perhaps like OutOfMemoryError which can occur even when unspecified.

In normal circumstances, the new Error/Exception might never be thrown. (The caller could catch if it is aware of the possibility, just as a memory-restricted Java program might specifically catch OOME.)

Is this therefore a valid argument for throwing an extra error and can I still claim to be a valid java.util.List (or pick your SDK/language/collection in general) and not in violation of LSP?

Edit: This argument might be more palatable if you consider a FileBackedList (more reliable "connection") rather than a DbBackedList.

If this does indeed violate LSP and thus not practically usable, I have provided two less-palatable alternative solutions as answers that you can comment on, see below.

Footnote: Use Cases

In the simplest case, the goal is to provide a familiar interface for cases when (say) a database is just being used as a persistent list, and allow regular List operations such as search, subList and iteration.

Another, more adventurous, use-case is as a slot-in replacement for libraries that work with basic Lists, e.g if we have a third-party task queue that usually works with a plain List:

new TaskWorkQueue(new ArrayList<String>()).start() which is susceptible to losing all it's queue in event of a crash, if we just replace this with:

new TaskWorkQueue(new DbBackedList()).start() we get a instant persistence and the ability to share the tasks amongst more than one machine.

In either case, we could either handle connection/read exceptions that are thrown, perhaps  retrying the connection/read first, or allow them to throw and crash the program (e.g. if we can't change the TaskWorkQueue code).


问:
C# vector class - Interpolation design decision
Currently I'm coding a Vector class in C# and I'm coming to the point, where I've to figure out, how I want to implement a function/method to interpolate between two vectors. The (obvious) and also my first solution was to simply implement it as a method in the vector class itself:

```<code>public class Vector3D
{
    public static Vector3D LinearInterpolate(Vector3D vector1,
        Vector3D vector2, double factor) { ... }

    public Vector3D LinearInterpolate(Vector3D other, double factor { ... }
}
</code>```

(I decided to offer both a static method with two vectors as parameters and one non-static, with only one vector as the parameter)

But then I got the idea to use extension methods (defined in a separate class called e.g. Interpolation for example), since interpolation isn't really limited to vectors only. So this might be another approach:

```<code>public class Vector3D { ... }

public static class Interpolation
{
    public static Vector3D LinearInterpolate(this Vector3D vector,
        Vector3D other, double factor) { ... }
}
</code>```

And here is an example showing how one would use the different implementations:

```<code>{
    var vec1 = new Vector3D(5, 3, 1);
    var vec2 = new Vector3D(4, 2, 0);
    Vector3D vec3;

    vec3 = vec1.LinearInterpolate(vec2, 0.5); //1
    vec3 = Vector3D.LinearInterpolate(vec1, vec2, 0.5); //2

    //or with extension-methods

    vec3 = vec1.LinearInterpolate(vec2, 0.5); //3 (same as 1)
    vec3 = Interpolation.LinearInterpolation(vec1, vec2,
    0.5); //4
}
</code>```

I can't really decide on which design is preferable. Is there a rule of thumb on how to implement methods/functions similar to the one above or is it rather a matter of preference? I really would like to hear your opinions on what's better and - if possible - why.

答:
Maybe it is that I come from Java, but I really don't like extension methods unless there is a good reason for it.

If you want to reuse the operation code, the solution should be composition. Create an Interpolator that operates over an IEnumerable<double> (unluckily, it seems that C# lacks an equivalent to java.lang.Number, so you can't make the class generic easily). I don't think it is a bad idea that your Vector class implements it, too.

For bonus points, make the class an interface that defines the operation and inject an instance of the interface in the object, so you can change the implementation (or even use other types of interpolations, if they match the method signature) at will.