问:
As a tooling/automation developer, can I be making better use of OOP?
My time as a developer (~8 yrs) has been spent creating tooling/automation of one sort or another. The tools I develop usually interface with one or more API's. These API's could be win32, WMI, VMWare, a help-desk application, LDAP, you get the picture. The apps I develop could be just to pull back data and store/report. It could be to provision groups of VM's to create live like mock environments, update a trouble ticket etc.

I've been developing in .Net and I'm currently reading into design patterns and trying to think about how I can improve my skills to make better use of and increase my understanding of OOP. For example, I've never used an interface of my own making in anger (which is probably not a good thing), because I honestly cannot identify where using one would benefit later on when modifying my code. My classes are usually very specific and I don't create similar classes with similar properties/methods which could use a common interface (like perhaps a car dealership or shop application might).

I generally use an n-tier approach to my apps, having a presentation layer, a business logic/manager layer which interfaces with layer(s) that make calls to the API's I'm working with. My business entities are always just method-less container objects, which I populate with data and pass back and forth between my API interfacing layer using static methods to proxy/validate between the front and the back end.

My code by nature of my work, has few common components, at least from what I can see. So I'm struggling to see how I can better make use of OOP design and perhaps reusable patterns.

Am I right to be concerned that I could be being smarter about how I work, or is what I'm doing now right for my line of work? Or, am I missing something fundamental in OOP?

EDIT: Here is some basic code to show how my mgr and api facing layers work. I use static classes as they do not persist any data, only facilitate moving it between layers.

```<code>public static class MgrClass
{
    public static bool PowerOnVM(string VMName)
    {
        // Perform logic to validate or apply biz logic
        // call APIClass to do the work
        return APIClass.PowerOnVM(VMName);
    }
}

public static class APIClass
{
    public static bool PowerOnVM(string VMName)
    {
        // Calls to 3rd party API to power on a virtual machine
        // returns true or false if was successful for example
    }
}
</code>```

答:
The key point of OOP that often gets lost in the acronym/pattern/kool-aid confusion is that you're thinking in terms of objects that govern problem domains interacting with each other rather than a pile of methods (or one-method classes with no other properties) that just run data through a series of hoops.

There are really only two things I focus on when thinking about how to write classes/constructors.

Encapsulation

When data is essentially just consumed and reprocessed through 20 method calls in long return/param chain that all live in different places, how different is that from just having a global var that they all act on? Altering the structure of that data still likely means you have to have to alter all 20 methods and debug who-dun-its will still require following a full trace to get to the source of a problem since there's no way to know what corner of an app was touching that data when it broke.

If data lives in one class and it only enters a given system via that class. You only have to validate, package, and canonicalize it once in that one place until you finally move it to some other object as some major step in a process (e.g. db layer to service handling class or service handling class to client).

Now it may seem I'm advocating gigantor classes that do everything under the sun. Not at all. The key thing to having a single-point of entry isn't to have huge classes (although I would say that SOLID has lead to devs thinking overly small classes are more appropriate than they often are in codebases I've worked in). But rather layer up by compositing as needed. Just make that point of entry stuff the responsibility of one higher-level class so whatever gets used inside it through compositing/internal classes doesn't have to.

Writing to an Interface

No, not the thing you tack on to a class definition to assert a contract in C#/Java. I mean the actual set of methods you're exposing as an API. The more you write your classes/objects as having a role to fill by providing a set of useful methods that give just enough granularity without making you re-do any of the pointless detail work, the less you'll be scooting data around and creating inflexibility and needless dependencies. And the less you'll be tempted to put tests and contracts on absolutely everything in your codebase because you've made a mess out of things by creating a needless hornets nest of dependencies.

The key thing is to stop thinking in terms of the series of steps to get from point A to point B to ... and instead think about who needs to be able to do what, establish those classes and methods and then fill in the blanks and get them working with each other.

The Wins You Should Be Getting

Easier to Read/Understand/Debug: At some higher level you should see a few objects interacting. And then see greater detail as you work your way down. Through this, it should be easier to narrow down which components of an app are responsible for a problem before you even set your first breakpoint. If you generally always debug by finding the trigger for something and tracing through the entire process without even trying to read the code like a human first, you're probably not employing very good OOD.

Easier to Modify: Encapsulating/designing well reduces dependencies. As long as a given class/object's interface does what it's expected to do you need never worry about how other changes you make in the interior will impact the rest of an app.

Easier to Reuse: Well-designed classes should make it easy to move large portions of related functionality into other codebases with a minimum of modification.

OwnerDisplayName: Tom Pickles


问:
Is it bad practice to run Node.js and apache in parallel?
I have an idea in mind and would like to know if that's the way to go for my end application.

Think of my application as a social networking system in which I want to implement chat functionality. For that, I'd like to push data from the server to the client. I have heard I could use Node.js for that.

In the meanwhile, I want a 'regular' system for posting status updates and such, for which I'd like to use PHP and an apache server.

The only way I can think of is having Node.js and apache running parallel. But is that the way to go here? I'd think there would be a somewhat neater solution for this.

答: There's no technical reason you couldn't do this. I did something very similar for a simple game I wrote to play with Node. The pages were served by Apache and written in PHP, but then I had an HTML5 canvas and I initialized a socket to my Node server. Both Apache and Node can run happily side by side on the same machine, just different ports.</p>

ContentLicense: CC BY-SA 3.0


问:
Organizing related projects and dependencies for nuget publishing
I've been working on writing .NET bindings for Rollbar, an error and message reporting service, like Airbrake. My library is working nicely and is published in the NuGet gallery.

So now I want to take it to the next level of usability and implement an NLog Extension for this. This entails writing one screen's-worth of code and referencing the NLog library. It's a wrapper. I may also implement one for Log4Net.

At this point it's already getting blurry as to how I should organize this and manage it with source control and nuget. One thing for sure is that there will be separate nuget packages so people don't have to install dependencies they don't want.

My questions are:

Should I create separate git repositories for the base library and NLog extension and Log4Net extension? Seems like it would be easier to track changes have clearly separated build processes and such. It may make contributing to the project(s) easier...but I'm not sure.

Should I reference my Rollbar base library as a dependency of the extension libraries, or ILMerge it? The upside to ILMerge is the user only needs one reference and DLL. The odd part is with versioning. Like how to have version numbers that make sense when only the base library changed, or only the extension changed. Also, it seems like nuget doesn't list updates to dependencies of installed packages, only to the packages itself. I'd want updates to the base library to bubble-up as an update the user should install! I suppose one way to do that would be version-bumping the extension and setting the version of the dependency library.

This is my first foray into writing an open source library and publishing it and managing it. I'd love some feedback from people who have dealt with this so I can get it right!

I'm using Albacore for my build process, for what it's worth.

(Current code: https://github.com/mroach/RollbarSharp)

答:
I wouldn't mind including a useless-to-me, small DLL as part of a bigger package, but I wouldn't want to include that and NLog, so that I can use Rollbar with log4net.

So, if you are going to include them in the main package, don't make the package dependent on the secondary product. Because it's not dependent. I don't need NLog to use Rollbar. But, note that this means I'll be able to install any version of NLog alongside Rollbar, which means I'm screwed if I pick one that's incompatible.

There are plenty of open-source projects on nuget that link two others and have combined names, like Rollbar.NLog, which makes them turn up next to Rollbar when I'm searching but gives me the choice whether to include them or not.

If you take that option, you can make version numbers independant, by setting dependency versions. For example, you say Rollbar.NLog v1.2 requires Rollbar v1.x (the dependency tag in your nuspec file, (id="Rollbar" version="[1.1,1.2)") and give me permission to upgrade the two packages independently, as long as neither is upgraded to v2.x.

If you have a Rollbar.NLog package then you should make it dependent on NLog. If you can be confident of NLog's versioning (eg. will always be backward compatible, unless the major version changes) then give me freedom with that too. But you don't have to. You can specify id="NLog" version="[3.2.1]". Doing so makes it safe for me, but less flexible -- my NLog upgrade strategy is tied to your release strategy.


问:
Ship Early, Ship Never
This started as a "Note to Self," so please excuse me if the frustration is all too evident and the writing is less than stellar...

Three major subjects I've had at the forefront of my mind lately:

Motivation

Learning (Curiosity)

Doing (Making)

I've been studying motivation and incentives for months now. It seems there are an infinite number of different motivations that people might have for doing things (I realize that sounds trite but bear with me). I've been really drawn to it because I'm desperate to find out why I do the things I do and why I don't do the things that I want to do but don't do.

I'm in the midst of reading Paul Graham's excellent Hackers and Painters book. In it, he makes the case that hackers and painters are very similar because they are both "makers." Painters make paintings. Hackers make software. Painters don't necessarily need to understand the chemical composition of paint to make beautiful paintings. And hackers don't necessarily need to know 1's and 0's to make beautiful software.

Graham then draws the distinction between disparate computer science fields:

some people seem to be studying mathematics

some people seem to be studying the computers themselves

the hackers are making software.

The difference is incredibly important. It seems the motivation for some is to make beautiful things. And the motivation for the others is to learn out of curiosity. Certain motivations seem obvious to me, but curiosity seems a bit less obvious. I would certainly consider myself as a curious person with a seemingly unquenchable thirst to learn just about everything I can. But this is exactly where the problem comes up.

The thing that scares me so much is that I desperately want to make things. I desperately want to do things. I want to write a book. I want to paint a painting. I want to compose a song. I want to do things like travel. But the strangeness is that I also want to learn things. I want to learn to play guitar. I want to learn about art history. I want to learn more about philosophy and literature.

The key seems to be the balance between learning and doing... between studying and making.

While I'm not sure how much one should learn about a given thing before doing it, I know for certain that I find myself constantly on one side rather than the other. As it stands now (and as far as I can tell I've always been this way), I am a learner and not a doer. I've read great books. I've practiced guitar for years. I've spent countless hours studying programming.

But I've written 0 books. I've composed 0 songs. I've coded 0 beautiful programs. I've painted 0 beautiful paintings. I've started 0 viable businesses.

The scary part of all this is that there are probably countless unfinished works of art in the world. Is this my misanthropic revenge against society and culture to never produce or finish any of the works of art that I start? Perhaps the worst part (aside from this being my natural inclination), is the fact that I f***ing know better. I just finished books like "Getting Things Done" and "Making Ideas Happen." I've aggregated and synthesized countless words of wisdom on how to do things and how to make things.

Imagine the horror of going through life without being able to do the things you want to do. If this is something you've struggled with (and hopefully overcome), please share. If not... perhaps some delicious pity would make me feel better.

[UPDATE: Just wanted to send a quick thanks to everyone that shared their thoughts. I deliberately left the question somewhat open-ended in hopes of encouraging discussion and having others refashion the central problem around their similar experience, and I think it worked out great... there's a lot of amazing insight here to work with and it was really helpful. Thanks again.]

答:
Probably the best question on P.SE I've read so far.

I highly suggest you to have a look at current Seth Godin's work on the subject. He calls it the Resistance produced by the Lizard Brain.

What is the Lizard Brain? My explanation... The lizard brain is the primitive, limbic system that overrides everything else in our brain: it is fear, sex, hunger, etc. Especially fear. And for many of us, myself included, it's what prevents us from blogging more, writing a new preface, updating a book, crafting a new presentation, etc.

Source: Shut Up Lizard Brain: I Am Not Procrastinating Today

Read the chapter about it in the book Linchpin. You may be interested in The Dip too.

Please document yourself on Procrastination too.

ContentLicense: CC BY-SA 2.5

Title: Ship Early, Ship Never


问:
Chosing a parser for a code beautifier
I'm in the planning stage of making a code beautifier (similar to AStyle or Uncrustify) - originally I was going to just contribute to one of those projects,
but reviewing their source led me to the conclusion that I have different design goals and that their source is written in a way that makes it difficult for an outsider to easily contribute. AStyle, for example, instead of building some sort of AST, uses over 100 state variables such as isInComment, foundClassHeader, isLineReady, etc.

I'm deciding between using scanner and parser generators (such as flex and bison) and writing my own parsing system. Which would be a better approach? I've been through a compilers class in university, so I do have some experience with scanning and parsing theory. Below are the advantages I've thought of for each:

Generators

Arguably simpler/faster to develop

Possibly more optimized than my initial stab at a custom parser, though a custom one might leave more room for improvement

Custom parser

Arguably easier to debug

Programmers seems to prefer custom lexers and parsers in past questions - "Anyone who wants a decent lexer doesn't use Lex"

Fewer dependencies

Could possibly allow for "fuzzier" parsing - since I'm just developing a beautifier, the parser wouldn't need to be nearly as strict or detailed as one for a compiler

Parallelization - flex and bison (or what I've seen of them) use global state. If I want to parse multiple files at once (in separate threads), a custom solution would be simpler to compartmentalize

答:
It's not a choice between flex/bison or nothing.  There are several options out there.  I used antlr for a recent project and found it very nice to work with.  Some things you might not have considered:

Lexers aren't that difficult, but parsers have a considerable number of gotchas you won't even realize until they hit you.  Widely used tools have already solved a bunch of problems you don't even know exist yet.

Your parser will still need to be just as strict as a compiler.  The difference will be you can use a simpler grammar in some places, but that will probably be offset by needing to use more complex grammar in other places.  For example, code beautifiers often want to preserve an intentional newline that a regular compiler just lumps into "whitespace."  If your language has a preprocessor, a beautifier will have to incorporate that into the grammar, whereas a compiler's parser won't.

Grammars are extremely difficult to debug.  Tools like antlr have devoted considerable effort to producing useful error messages.  Even if you do go with a custom parser, you may still find it useful to use an existing parser generator to debug your grammar.

Title: Chosing a parser for a code beautifier


答:
Running several web server processes in parallel is not a problem at all, people do it all the time.

However, since only one process can ever listen on any given port, they can't both run on port 80 directly, so you'll have to dispatch somehow. An easy solution is to run the Node.js application on a custom port (anything above 1024 should be fair game, but do a bit of research first, and make it configurable), then set up a reverse proxy in apache to pass it through on port 80 (or 443 if you need SSL) for the URLs that should go to Node.

Reverse proxying from Node into apache might also be possible, and if the Node application handles the most performance-critical calls, it may or may not be a better solution.

A thirds solution is to serve them both on different ports and do the reverse proxying in a separate process, or even a separate machine. The advantage of this is that splitting the setup over more application servers (e.g. dedicated boxes for the Node and PHP parts) later is relatively trivial (but then, it isn't much harder for the other two solutions either).

The nice part about having Apache on the public-facing side is that you can use its various mature features such as HTTP authentication, rewriting, SSL, virtual hosts, static file serving, etc., so the Node part can focus on the essentials. No need to reinvent the wheel there.

Title: Is it bad practice to run Node.js and apache in parallel?

Body:
I have an idea in mind and would like to know if that's the way to go for my end application.

Think of my application as a social networking system in which I want to implement chat functionality. For that, I'd like to push data from the server to the client. I have heard I could use Node.js for that.

In the meanwhile, I want a 'regular' system for posting status updates and such, for which I'd like to use PHP and an apache server.

The only way I can think of is having Node.js and apache running parallel. But is that the way to go here? I'd think there would be a somewhat neater solution for this.


问:
Deploy PHP project without giving away the source code?
I am working on developing range of web based software solutions. But the problem is that for some clients we need to deploy the applications in their local intranet. In such a situation I have to stick with Java as development language as I cannot give away the source code of the project.

Now in order to tap on more consumers we put these solutions online. Now considering the fact that Java hosting is more expensive than PHP we are left with no choice but to again re develop the entire solution in PHP. Thus we end up having two version of same solution for maintenance and upgrading in different platforms.

So can any point us to some good solution in which we can have the online solution and also have a deployable version of the application in which we can ship the application without its source code and at the same time we also need the application to be cost effective from hosting point of view?

答:
Have you considered a virtual machine appliance? That's how GitHub does it for GitHub Enterprise, and how Microsoft does it for their beta software (particularly early stage beta).

This provides a few different advantages:

Restricts client access to code. In GitHub's case, this means that their non-open-sourced core components remain out of the sight of clients, and there's no fuss with NDAs or whathaveyou. The appliance is deployed, everything runs automatically, and it's all accessed and administered via the web interfaces.

Ensures a stable, controlled deployment environment. Nothing's more of a pain than to deploy to someone else's server, only to find out that they're running an old version of PHP and can't upgrade, or worse, they're running an old version of Windows Server that doesn't allow PHP at all. Deploy a virtual machine, and you have full control over that environment.

Sandboxes the install. This goes hand in hand with #2, but subtly different. Microsoft's betas are a good example of the use case for this. Beta software is notorious for being prone to stability issues (it's beta, go figure). Providing it in a virtual machine allows it to crash and burn without taking out the user's entire system. The same holds true for the inverse - keeping your application in a virtual machine protects it from another piece of software crashing and burning (of course, if the host system as a whole goes down, that's a different matter, but other things running on the host machine will have little impact on your software).


问:
Branching library behavior based on 3rd party library existence
Someone proposed to me this pattern which I have never heard of before and can't find any information on it.

The basic idea is, when building a library for other developers to use; if the developer includes my library along with a 3rd party library the behavior of the API calls to my library changes.

An example:

I have a library/API for inserting, getting, updating, deleting on a database.

Developer includes a 3rd party database encryption library.

My library/API changes to require a "unencrypt(password)" call to be made before inserting, getting, updating, deleting.

Is this a safe practice?  Is there anything else out there like it?  What advantages and disadvantages are there to this pattern?

答:
Essentially what you are saying is that you'd like to design your library to have a dependency on a third-party library, and fall back to some default behavior if that third-party library is not available.

I think this is perfectly acceptable as long as it is well-documented.

If you are asking whether it is acceptable for an API call to do two entirely different things, I would say no. The meaning of the API call should not change depending on the presence of another library.


答: Interesting question for sure. Like a lot of things in life, I believe balance is very important - you seem to think your "doing" is out of balance with your "learning" so do more ! Correct the balance. Remember, you are the only person that can make you happy.</p>

Title: Ship Early, Ship Never

Body:
This started as a "Note to Self," so please excuse me if the frustration is all too evident and the writing is less than stellar...

Three major subjects I've had at the forefront of my mind lately:

Motivation

Learning (Curiosity)

Doing (Making)

I've been studying motivation and incentives for months now. It seems there are an infinite number of different motivations that people might have for doing things (I realize that sounds trite but bear with me). I've been really drawn to it because I'm desperate to find out why I do the things I do and why I don't do the things that I want to do but don't do.

I'm in the midst of reading Paul Graham's excellent Hackers and Painters book. In it, he makes the case that hackers and painters are very similar because they are both "makers." Painters make paintings. Hackers make software. Painters don't necessarily need to understand the chemical composition of paint to make beautiful paintings. And hackers don't necessarily need to know 1's and 0's to make beautiful software.

Graham then draws the distinction between disparate computer science fields:

some people seem to be studying mathematics

some people seem to be studying the computers themselves

the hackers are making software.

The difference is incredibly important. It seems the motivation for some is to make beautiful things. And the motivation for the others is to learn out of curiosity. Certain motivations seem obvious to me, but curiosity seems a bit less obvious. I would certainly consider myself as a curious person with a seemingly unquenchable thirst to learn just about everything I can. But this is exactly where the problem comes up.

The thing that scares me so much is that I desperately want to make things. I desperately want to do things. I want to write a book. I want to paint a painting. I want to compose a song. I want to do things like travel. But the strangeness is that I also want to learn things. I want to learn to play guitar. I want to learn about art history. I want to learn more about philosophy and literature.

The key seems to be the balance between learning and doing... between studying and making.

While I'm not sure how much one should learn about a given thing before doing it, I know for certain that I find myself constantly on one side rather than the other. As it stands now (and as far as I can tell I've always been this way), I am a learner and not a doer. I've read great books. I've practiced guitar for years. I've spent countless hours studying programming.

But I've written 0 books. I've composed 0 songs. I've coded 0 beautiful programs. I've painted 0 beautiful paintings. I've started 0 viable businesses.

The scary part of all this is that there are probably countless unfinished works of art in the world. Is this my misanthropic revenge against society and culture to never produce or finish any of the works of art that I start? Perhaps the worst part (aside from this being my natural inclination), is the fact that I f***ing know better. I just finished books like "Getting Things Done" and "Making Ideas Happen." I've aggregated and synthesized countless words of wisdom on how to do things and how to make things.

Imagine the horror of going through life without being able to do the things you want to do. If this is something you've struggled with (and hopefully overcome), please share. If not... perhaps some delicious pity would make me feel better.

[UPDATE: Just wanted to send a quick thanks to everyone that shared their thoughts. I deliberately left the question somewhat open-ended in hopes of encouraging discussion and having others refashion the central problem around their similar experience, and I think it worked out great... there's a lot of amazing insight here to work with and it was really helpful. Thanks again.]


问:
Why is it a good idea for "lower" application layers not to be aware of "higher" ones?
In a typical (well-designed) MVC web app, the database is not aware of the model code, the model code is not aware of the controller code, and the controller code is not aware of the view code. (I imagine you could even start as far down as the hardware, or perhaps even further, and the pattern might be the same.)

Going the other direction, you can go just one layer down. The view can be aware of the controller but not the model; the controller can be aware of the model but not the database; the model can be aware of the database but not the OS. (Anything deeper is probably irrelevant.)

I can intuitively grasp why this is a good idea but I can't articulate it. Why is this unidirectional style of layering a good idea?

答:
Just for fun.

Think of a pyramid of cheerleaders.  The bottom row is supporting the rows above them.

If the cheerleader on that row is looking down they are stable and will stay balanced so that those above her don't fall.

If she looks up to see how everyone above her is doing, she will loose her balance causing the whole stack to fall down.

Not really technical, but it was an analogy I thought might help.


答:
For your online customers have you looked at the SAAS model?

This would allow you to host all your web clients on your own servers.

Title: Deploy PHP project without giving away the source code?

Body:
I am working on developing range of web based software solutions. But the problem is that for some clients we need to deploy the applications in their local intranet. In such a situation I have to stick with Java as development language as I cannot give away the source code of the project.

Now in order to tap on more consumers we put these solutions online. Now considering the fact that Java hosting is more expensive than PHP we are left with no choice but to again re develop the entire solution in PHP. Thus we end up having two version of same solution for maintenance and upgrading in different platforms.

So can any point us to some good solution in which we can have the online solution and also have a deployable version of the application in which we can ship the application without its source code and at the same time we also need the application to be cost effective from hosting point of view?


问:
A programming language that allows you to define new limits for simple types
Many languages like C++, C#, and Java allow you to create objects that represent simple types like integer or float. Using a class interface you can override operators and perform logic like checking if a value exceeds a business rule of 100.

I'm wondering if it's possible in some languages to define these rules as annotations or attributes of a variable/property.

For example, in C# you might write:

```<code>[Range(0,100)]
public int Price { get; set; }
</code>```

Or maybe in C++ you could write:

```<code>int(0,100) x = 0;
</code>```

I've never seen something like this done, but given how dependent we have become on data validation before storage. It's strange that this feature hasn't been added to languages.

Can you give example of languages where this is possible?

答:
Pascal had subrange types, i.e. decreasing the number of numbers that fit into a variable.

```<code>  TYPE name = val_min .. val_max;
</code>```

Ada also has a notion of ranges: http://en.wikibooks.org/wiki/Ada_Programming/Types/range

From Wikipedia....

```<code>type Day_type   is range    1 ..   31;
type Month_type is range    1 ..   12;
type Year_type  is range 1800 .. 2100;
type Hours is mod 24;
type Weekday is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
</code>```

can also do

```<code>subtype Weekend is  Weekday (Saturday..Sunday);
subtype WorkDay is  Weekday (Monday..Friday);
</code>```

And here's where it gets cool

```<code>year : Year_type := Year_type`First -- 1800 in this case......
</code>```

C does not have a strict subrange type, but there are ways to mimic one (at least limited) by using bitfields to minimize the number of bits used. struct {int a : 10;} my_subrange_var;}. This can work as an upper bound for variable content (in general I would say: don't use bitfields for this, this is just to proof a point).

A lot of solutions for arbitrary-length integer types in other languages rather happen on the library-level, I.e. C++ allows for template based solutions.

There are languages that allow for monitoring of variable states and connecting assertions to it. For example in Clojurescript

```<code>(defn mytest
   [new-val]
   (and (< new-val 10)
        (<= 0 new-val)))

(def A (atom 0 :validator mytest))
</code>```

The function mytest is called when a has changed (via reset! or swap!) checks whether conditions are met. This could be an example for implementing subrange behaviour in late-binding languages (see http://blog.fogus.me/2011/09/23/clojurescript-watchers-and-validators/ ).

Body:
Pascal had subrange types, i.e. decreasing the number of numbers that fit into a variable.

  TYPE name = val_min .. val_max;

Ada also has a notion of ranges: http://en.wikibooks.org/wiki/Ada_Programming/Types/range

From Wikipedia....

type Day_type   is range    1 ..   31;
type Month_type is range    1 ..   12;
type Year_type  is range 1800 .. 2100;
type Hours is mod 24;
type Weekday is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);

can also do

subtype Weekend is  Weekday (Saturday..Sunday);
subtype WorkDay is  Weekday (Monday..Friday);

And here's where it gets cool

year : Year_type := Year_type`First -- 1800 in this case......

C does not have a strict subrange type, but there are ways to mimic one (at least limited) by using bitfields to minimize the number of bits used. struct {int a : 10;} my_subrange_var;}. This can work as an upper bound for variable content (in general I would say: don't use bitfields for this, this is just to proof a point).

A lot of solutions for arbitrary-length integer types in other languages rather happen on the library-level, I.e. C++ allows for template based solutions.

There are languages that allow for monitoring of variable states and connecting assertions to it. For example in Clojurescript

(defn mytest
   [new-val]
   (and (< new-val 10)
        (<= 0 new-val)))

(def A (atom 0 :validator mytest))

The function mytest is called when a has changed (via reset! or swap!) checks whether conditions are met. This could be an example for implementing subrange behaviour in late-binding languages (see http://blog.fogus.me/2011/09/23/clojurescript-watchers-and-validators/ ).


问:
End-to-end tests versus unit tests, should tests be decoupled?
At our company we typically make sure that we write an end-to-end test for our websites/web apps. That means we access a URL, fill in a form, submit the form to another URL and check the results of the page. We do this to test form validation, test that the HTML templates have the correct context variables, etc.

We also use it to indirectly test the underlying logic.

I was told by a co-worker that the reason for this is that we can rip out and change the underlying implementation at any point as long as the end-to-end tests pass.

I'm wondering if this sort of decoupling makes sense or if it's just a way to avoid writing tests for smaller units of code?

答: Yes, end-to-end tests (or integration tests) make a lot of sense, but so do unit tests, too. Ideally, you have both of them, since both typically catch different kind of bugs. Thus, having end-to-end tests should never be an excuse for not having unit tests. </p>


问:
Subranges in Pascal
I'm reading some Pascal code and everything is pretty straightforward except subranges. In the program I'm reading there's a variable d with the following type declaration:array[0..22] of 0..15; there's then the following procedure:

```<code>
var a:integer;
begin
  a:=0;
  while k>0 do
    begin
      k:=k-1;
      a:=(a+dig[k]*two) div 10;
    end;
  round_decimals:=(a+1) div 2;
end;
</code>```

Where k is a variable of type 0..63. So since k can be above the range of the index of dig how does this code work? — It's a routine for doing fixed point arithmetic and so I would assume the array indicie overflows in some controlled manner, but if anybody could explain the exact behavior I'd be really happy. Also, do Pascal arrays assign in some known manner? There were a lot of versions of Pascal and I think this program is written in a pretty “Pascal-version agnostic” manner, but I can't find much explanation on the subtle semantics of subrange expressions.

答: It depends on the Pascal variant.  In managed versions, like Oxygene or the DWS scripting language, assigning out of bounds of an array will always raise an exception at runtime.  In Delphi and FPC, assigning out of bounds of an array should raise an exception at runtime, and does by default, but there's an option to turn bounds checking off via a compiler directive.  The behavior of other Pascal compilers will vary, based on whether or not they generate bounds checking code.

Title: Subranges in Pascal


答:
End-to-end tests are also necessary.  How else can you know you hooked up all the units together correctly?  On very simple code, it is possible to test all the paths through the code with only end-to-end tests, but as you get more layers, it becomes prohibitively more costly to do so.

For example, say you have three layers, each with five possible paths.  To test all the paths through the entire application would require 53 end-to-end tests, but you can test all the paths through each unit with only 5·3 unit tests.  If you only do end-to-end testing, a lot of paths end up getting neglected, mostly in error handling and boundary conditions.

Title: End-to-end tests versus unit tests, should tests be decoupled?

Body:
At our company we typically make sure that we write an end-to-end test for our websites/web apps. That means we access a URL, fill in a form, submit the form to another URL and check the results of the page. We do this to test form validation, test that the HTML templates have the correct context variables, etc.

We also use it to indirectly test the underlying logic.

I was told by a co-worker that the reason for this is that we can rip out and change the underlying implementation at any point as long as the end-to-end tests pass.

I'm wondering if this sort of decoupling makes sense or if it's just a way to avoid writing tests for smaller units of code?


问:
Sub-Resource data should be embedded in Resource entity or duplicated in NoSQL document?
I have a scenario similar to as depicted below,

```<code>public class Post {
    private int id;
    private int postType;
    private int score;
    private User originalPoster;
    private String title;
    private String body;
    private String tags;

}

public class Comment {
    private int id;
    private int postId;
    private String text;
    private int score;
    private User userId;
}

public class User {
    int id;
    String displayName;
    int score;
}
</code>```

How do I model my MongoDb document/domain object?

My initial options are,

1) Have a separate Post and Comment collections and handle updates/retrievals hide behind my Rest Resource with possible duplicate of Comment in both Post and Comment.

2) Have a single Document Post and include everything in it and have only one Rest Resource? This will limit my url templates or need for complex data retrievals at MongoDB end.

Whether I should go with 1) or 2) or there is other approach where I can have flexibility of urltemplates and minimize the NoSQL interactions?

答:
I'll preface this with a disclaimer -- I have zero seat time in MongoDb. I do have a fair amount of seat time in some other document databases and I think these problems are similar. But there could be some mongo specific stuff I might miss here -- I have no idea what url templates are or how one would use them.

With document databases, in general the best approach would be to think about your transaction boundaries here -- that should be how one defines what is in a given document. For example, are you always dealing with posts and comments or sometimes just posts? Do you have angles where you need to deal with comments on an individual level?

Another issue is practical concerns -- like the case where you have a hot post with 15,000 comments. Even at 1kb / comment you are looking at some pretty nasty load times if you just want to show that post.

Anyhow, I would probably make everything a post and add a field for "parentPostId" or something like that. Then I would model the PostsWithComments as an index rather than a concrete document which should give you the best of both worlds -- easy to get full post data while keeping writes and other maintenance sane. Indexes are your best friend here.


答: Figured it out; the ranges were chosen for alignment/offsets. Since Pascal (at least the old version of Pascal I'm reading) doesn't have short ints, etc. this was the alternative. Glad I don't write Pascal code. Anyway, it really had nothing to do with bounds checking and d[...] was pre-loaded in case anybody is wondering (I doubt it). Case closed.</p>

Title: Subranges in Pascal

Body:
I'm reading some Pascal code and everything is pretty straightforward except subranges. In the program I'm reading there's a variable d with the following type declaration:array[0..22] of 0..15; there's then the following procedure:

```<code>
var a:integer;
begin
  a:=0;
  while k>0 do
    begin
      k:=k-1;
      a:=(a+dig[k]*two) div 10;
    end;
  round_decimals:=(a+1) div 2;
end;
</code>```

Where k is a variable of type 0..63. So since k can be above the range of the index of dig how does this code work? — It's a routine for doing fixed point arithmetic and so I would assume the array indicie overflows in some controlled manner, but if anybody could explain the exact behavior I'd be really happy. Also, do Pascal arrays assign in some known manner? There were a lot of versions of Pascal and I think this program is written in a pretty “Pascal-version agnostic” manner, but I can't find much explanation on the subtle semantics of subrange expressions.


问:
Disagreement Concerning Data Integration (I may not understand enterprise ETL tools)
I have been in an ongoing conversation concerning a project we are about to undertake at my place at work.  The project concerns data integration.  Our customers want to be able to integrate our data with theirs, either by sending data from their systems into ours, or by getting data from our system into theirs.  I don't believe we are talking about 'big data.'  Our entire database is less than 20 gigs.

The individual transfers from our customers will be very small as well - on the order of 10s of MBs, if not smaller.

A major goal for this project is to minimize the amount of work needed to be done by the customer, who tends to not be very technical.  In the past, this problem has been "solved" by having our customers send us an xml file that is transformed by xlst before being saved to the database, or through a WCF application for exporting data.  These are not seen as good solutions.

My first thought was to create a REST interface with very good monitoring tools and libraries for our clients.

Another option that is being considered are big tools like IBM datastage or Pentaho (or similar).

My personal problem is that when I look at these tools, I don't see how they can help.  It looks like they are aimed at setting up large scale data transfers that happen on a regular schedule with a given format.  Adding a new import/export using those tools requires a lot of setup both for us and the customer, which we are trying to avoid.  They are also not really useful for real-time data updates. Finally, they seem like they are trying to kill an ant with a flamethrower - they are heavyweights for a light weight problem.

In contrast, with a REST setup, data can be transferred whenever required, and Setup only needs to happen in a very small area.

Am I missing something when it comes to these ETL solutions?  Am I not being fair to them?

答:
Additionally to connectivity provided by REST interfaces or FTP file transfers, you will require a certain degree of data security and fault tolerance. Therefore, my recommendation is to use AS2 as secure and reliable message transfer. Mail transfer of XML messages (secured via S/MIME X.509 PKI certificates) might be a bit slow for you but would be an option to consider.

There are quite a few aspects to take into account when selecting the "best" business-to-business solution:

Reliability (error avoidance and error handling)

Flexibility (time/effort to establish new connections)

Operating cost

Monitoring (technical and on business-level)

Investments for software and hardware

Throughput (data volume per time period)

Latency (end-to-end delay for messages)

Privacy

Fraud detection/prevention

Adherence to standards and regulations

Availability of knowledgeable consultants

Number of messages and maximum message size

Message operations required (signature validation, compression, routing, mapping,
format/content checking)

Management of partner data (addresses, ports, formats, etc.)

Archiving (for audits and support)

The domain of ETL is data migration and "big data". A typical use case for ETL is loading thousands of Gigabytes into a datawarehouse for business intelligence purposes.


问:
Where is interface between button click and event raising defined
When I click on button, might be in windows apps, web apps, etc it has some animation to actually see it clicked and event is raised in background. I've knowledge of events and its attaching to button click events but I wanted to know how this mechanism works. I always assumed it is inbuilt in operating systems.</p>

答:
There really isn't an interface.  There is the object that raises the event and then a delegate(s) that handles the event.  The object that raises the event has no idea who/what/how the event will be handled.  It just raises the event with any relevant data on the message so that the delegate(s) can handle it properly.

The delegate has to register itself as a handler for that event.

Something like this:

```<code>button1.Click += new EventHandler(button1Click);
</code>```

Then there will be the method that will handle the event:

```<code>void button1Click(object obj, EventArgs e)
{
    //Do Something with the click
}
</code>```

Its not garanteed that "Event Driven Programming Model" will exist on your platform or environment.  It so happens on Windows that this is supported.

With .Net, the support is baked with the ability to raise events and use delegates to handle them.  There also built in async support as well.

Underlying, the OS (Windows) has a message pump or loop which is constantly cycling and handling messages that are posted.  Typically, in higher level languages you do not have to interact with the internals as these are shielded from you from the framework with namespaces such as System.Windows.Forms.  But you can get close to the message pump by working with the Windows API directly (if you want to).

You can learn more abou the message pump here:

https://stackoverflow.com/questions/2222365/what-is-a-message-pump

Body:
There really isn't an interface.  There is the object that raises the event and then a delegate(s) that handles the event.  The object that raises the event has no idea who/what/how the event will be handled.  It just raises the event with any relevant data on the message so that the delegate(s) can handle it properly.

The delegate has to register itself as a handler for that event.

Something like this:

button1.Click += new EventHandler(button1Click);

Then there will be the method that will handle the event:

void button1Click(object obj, EventArgs e)
{
    //Do Something with the click
}

Its not garanteed that "Event Driven Programming Model" will exist on your platform or environment.  It so happens on Windows that this is supported.

With .Net, the support is baked with the ability to raise events and use delegates to handle them.  There also built in async support as well.

Underlying, the OS (Windows) has a message pump or loop which is constantly cycling and handling messages that are posted.  Typically, in higher level languages you do not have to interact with the internals as these are shielded from you from the framework with namespaces such as System.Windows.Forms.  But you can get close to the message pump by working with the Windows API directly (if you want to).

You can learn more abou the message pump here:

https://stackoverflow.com/questions/2222365/what-is-a-message-pump


答:
Some restricted form of your intention is to my knowledge possible in Java and C# through a combination of Annotations and Dynamic Proxy Pattern (there exist built-in implementations for dynamic proxies in Java and C#).

Java version

The annotation:

```<code>@Target(ElementType.PARAMETER)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface IntRange {
     int min ();
     int max ();
}
</code>```

The Wrapper class creating the Proxy instance:

```<code>public class Wrapper {
    public static Object wrap(Object obj) {
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new MyInvocationHandler(obj));
    }
}
</code>```

The InvocationHandler serving as bypass at every method call:

```<code>public class MyInvocationHandler implements InvocationHandler {
    private Object impl;

    public MyInvocationHandler(Object obj) {
        this.impl = obj;
    }

@Override
public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable {
    Annotation[][] parAnnotations = method.getParameterAnnotations();
    Annotation[] par = null;
    for (int i = 0; i<parAnnotations.length; i++) {
        par = parAnnotations[i];
        if (par.length > 0) {
            for (Annotation anno : par) {
                if (anno.annotationType() == IntRange.class) {
                    IntRange range = ((IntRange) anno);
                    if ((int)args[i] < range.min() || (int)args[i] > range.max()) {
                        throw new Throwable("int-Parameter "+(i+1)+" in method \""+method.getName()+"\" must be in Range ("+range.min()+","+range.max()+")");
                    }
                }
            }
        }
    }
    return method.invoke(impl, args);
}
}
</code>```

The Example-Interface for Usage:

```<code>public interface Example {
    public void print(@IntRange(min=0,max=100) int num);
}
</code>```

Main-Method:

```<code>Example e = new Example() {
    @Override
    public void print(int num) {
        System.out.println(num);
    }
};
e = (Example)Wrapper.wrap(e);
e.print(-1);
e.print(10);
</code>```

Output:

```<code>Exception in thread "main" java.lang.reflect.UndeclaredThrowableException
at com.sun.proxy.$Proxy0.print(Unknown Source)
at application.Main.main(Main.java:13)
Caused by: java.lang.Throwable: int-Parameter 1 in method "print" must be in Range (0,100)
at application.MyInvocationHandler.invoke(MyInvocationHandler.java:27)
... 2 more
</code>```

C#-Version

The annotation (in C# called attribute):

```<code>[AttributeUsage(AttributeTargets.Parameter)]
public class IntRange : Attribute
{
    public IntRange(int min, int max)
    {
        Min = min;
        Max = max;
    }

    public virtual int Min { get; private set; }

    public virtual int Max { get; private set; }
}
</code>```

The DynamicObject Sub-Class:

```<code>public class DynamicProxy : DynamicObject
{
    readonly object _target;

    public DynamicProxy(object target)
    {
        _target = target;
    }

    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
    {
        TypeInfo clazz = (TypeInfo) _target.GetType();
        MethodInfo method = clazz.GetDeclaredMethod(binder.Name);
        ParameterInfo[] paramInfo = method.GetParameters();
        for (int i = 0; i < paramInfo.Count(); i++)
        {
            IEnumerable<Attribute> attributes = paramInfo[i].GetCustomAttributes();
            foreach (Attribute attr in attributes)
            {
                if (attr is IntRange)
                {
                    IntRange range = attr as IntRange;
                    if ((int) args[i] < range.Min || (int) args[i] > range.Max)
                        throw new AccessViolationException("int-Parameter " + (i+1) + " in method \"" + method.Name + "\" must be in Range (" + range.Min + "," + range.Max + ")");
                }
            }
        }

        result = _target.GetType().InvokeMember(binder.Name, BindingFlags.InvokeMethod, null, _target, args);

        return true;
    }
}
</code>```

The ExampleClass:

```<code>public class ExampleClass
{
    public void PrintNum([IntRange(0,100)] int num)
    {
        Console.WriteLine(num.ToString());
    }
}
</code>```

Usage:

```<code>    static void Main(string[] args)
    {
        dynamic myObj = new DynamicProxy(new ExampleClass());
        myObj.PrintNum(99);
        myObj.PrintNum(-5);
    }
</code>```

In conclusion, you see that you can get something like that to work in Java, but it's not entirely convenient, because

Proxy class can just be instantiated for interfaces, i.e. your class has to implement an interface

Allowed Range can only be declared on interface level

Later usage comes just with extra effort in the beginning (MyInvocationHandler, wrapping at every instantiation) which also slightly reduces understandability

The capabilities of DynamicObject class in C# remove the interface restriction, as you see in the C# implementation. Unfortunately, this dynamic behavior removes static type safety in in this case, so runtime checks are necessary to determine if a method call on the dynamic proxy is allowed.

If those restrictions are acceptable for you, then this can serve as a basis for further digging!

Title: A programming language that allows you to define new limits for simple types

Body:
Many languages like C++, C#, and Java allow you to create objects that represent simple types like integer or float. Using a class interface you can override operators and perform logic like checking if a value exceeds a business rule of 100.

I'm wondering if it's possible in some languages to define these rules as annotations or attributes of a variable/property.

For example, in C# you might write:

```<code>[Range(0,100)]
public int Price { get; set; }
</code>```

Or maybe in C++ you could write:

```<code>int(0,100) x = 0;
</code>```

I've never seen something like this done, but given how dependent we have become on data validation before storage. It's strange that this feature hasn't been added to languages.

Can you give example of languages where this is possible?

Body:
Some restricted form of your intention is to my knowledge possible in Java and C# through a combination of Annotations and Dynamic Proxy Pattern (there exist built-in implementations for dynamic proxies in Java and C#).

Java version

The annotation:

@Target(ElementType.PARAMETER)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface IntRange {
     int min ();
     int max ();
}

The Wrapper class creating the Proxy instance:

public class Wrapper {
    public static Object wrap(Object obj) {
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new MyInvocationHandler(obj));
    }
}

The InvocationHandler serving as bypass at every method call:

public class MyInvocationHandler implements InvocationHandler {
    private Object impl;

    public MyInvocationHandler(Object obj) {
        this.impl = obj;
    }

@Override
public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable {
    Annotation[][] parAnnotations = method.getParameterAnnotations();
    Annotation[] par = null;
    for (int i = 0; i<parAnnotations.length; i++) {
        par = parAnnotations[i];
        if (par.length > 0) {
            for (Annotation anno : par) {
                if (anno.annotationType() == IntRange.class) {
                    IntRange range = ((IntRange) anno);
                    if ((int)args[i] < range.min() || (int)args[i] > range.max()) {
                        throw new Throwable("int-Parameter "+(i+1)+" in method \""+method.getName()+"\" must be in Range ("+range.min()+","+range.max()+")");
                    }
                }
            }
        }
    }
    return method.invoke(impl, args);
}
}

The Example-Interface for Usage:

public interface Example {
    public void print(@IntRange(min=0,max=100) int num);
}

Main-Method:

Example e = new Example() {
    @Override
    public void print(int num) {
        System.out.println(num);
    }
};
e = (Example)Wrapper.wrap(e);
e.print(-1);
e.print(10);

Output:

Exception in thread "main" java.lang.reflect.UndeclaredThrowableException
at com.sun.proxy.$Proxy0.print(Unknown Source)
at application.Main.main(Main.java:13)
Caused by: java.lang.Throwable: int-Parameter 1 in method "print" must be in Range (0,100)
at application.MyInvocationHandler.invoke(MyInvocationHandler.java:27)
... 2 more

C#-Version

The annotation (in C# called attribute):

[AttributeUsage(AttributeTargets.Parameter)]
public class IntRange : Attribute
{
    public IntRange(int min, int max)
    {
        Min = min;
        Max = max;
    }

    public virtual int Min { get; private set; }

    public virtual int Max { get; private set; }
}

The DynamicObject Sub-Class:

public class DynamicProxy : DynamicObject
{
    readonly object _target;

    public DynamicProxy(object target)
    {
        _target = target;
    }

    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
    {
        TypeInfo clazz = (TypeInfo) _target.GetType();
        MethodInfo method = clazz.GetDeclaredMethod(binder.Name);
        ParameterInfo[] paramInfo = method.GetParameters();
        for (int i = 0; i < paramInfo.Count(); i++)
        {
            IEnumerable<Attribute> attributes = paramInfo[i].GetCustomAttributes();
            foreach (Attribute attr in attributes)
            {
                if (attr is IntRange)
                {
                    IntRange range = attr as IntRange;
                    if ((int) args[i] < range.Min || (int) args[i] > range.Max)
                        throw new AccessViolationException("int-Parameter " + (i+1) + " in method \"" + method.Name + "\" must be in Range (" + range.Min + "," + range.Max + ")");
                }
            }
        }

        result = _target.GetType().InvokeMember(binder.Name, BindingFlags.InvokeMethod, null, _target, args);

        return true;
    }
}

The ExampleClass:

public class ExampleClass
{
    public void PrintNum([IntRange(0,100)] int num)
    {
        Console.WriteLine(num.ToString());
    }
}

Usage:

    static void Main(string[] args)
    {
        dynamic myObj = new DynamicProxy(new ExampleClass());
        myObj.PrintNum(99);
        myObj.PrintNum(-5);
    }

In conclusion, you see that you can get something like that to work in Java, but it's not entirely convenient, because

Proxy class can just be instantiated for interfaces, i.e. your class has to implement an interface

Allowed Range can only be declared on interface level

Later usage comes just with extra effort in the beginning (MyInvocationHandler, wrapping at every instantiation) which also slightly reduces understandability

The capabilities of DynamicObject class in C# remove the interface restriction, as you see in the C# implementation. Unfortunately, this dynamic behavior removes static type safety in in this case, so runtime checks are necessary to determine if a method call on the dynamic proxy is allowed.

If those restrictions are acceptable for you, then this can serve as a basis for further digging!


答:
The mouse hardware sends very simple messages on the USB bus when appropriate, essentially "button x was pressed/released" and "moved this much in the x and y directions since the last message I sent."

The USB driver on the computer has either been polling for these messages (checking periodically), or receives an interrupt, which is a mechanism built into the hardware that says, "I have a new USB message so I'm running code at a particular location."

The USB driver passes the message to the mouse driver in the kernel.

The mouse driver passes the message to the graphics subsystem (like xorg on Linux).

The graphics subsystem keeps track of the absolute position of the mouse, updating it from the relative position messages the mouse driver sends.

The graphics subsystem passes events to the window manager (like mutter).

The window manager keeps track of which window is under the mouse, and passes click events to the windowing toolkit (like Qt) associated with that window.

The windowing toolkit keeps track of which button is under the mouse, performs the click animation using graphics primitives, and passes events to subscribed listeners.

Obviously the implementation is different for different operating systems.  In particular Windows lumps a lot of the layers together for the programmer and user point of view, but that's the basic lay of the land.  I gave you some names for Linux because those are open source and if you were so inclined you could trace everything from the silicon on up.  Qt and other widget toolkits, which seems to be the part you're most interested in, are also available for Windows.

It's pretty amazing to contemplate the precise flow of electrons needed starting at the mouse button switch, through the CPU, out to the Internet and back through countless routers and servers, back through your CPU, eventually resulting in every single pixel on your display being commanded to its own specific color.  We sum up that result of millions of hours of collaborative effort simply as "clicking a link."

Title: Where is interface between button click and event raising defined

Body: When I click on button, might be in windows apps, web apps, etc it has some animation to actually see it clicked and event is raised in background. I've knowledge of events and its attaching to button click events but I wanted to know how this mechanism works. I always assumed it is inbuilt in operating systems.</p>


答: I also have the drive to make things as well as learn. I found that in order to become better at making something is to make things. For instance, I would like to compose music as well, but have never created a piece that I thought was good. However, they've gotten better as I've studied and practiced my instrument. On the other hand, I have programmed for nearly 10 years now, and I've created some pretty neat stuff. I also have learned a ton about how computers work and don't plan on stopping anytime soon. So, don't give up! If you want to create, start creating! The first tries won't be good, so what? They'll get better. If in yuor life you only are able to create one thing that you feel is really good, than that's still better than being frustrated over not doing anything. Keep on truckin'.</p>

Title: Ship Early, Ship Never


答:
See Limiting range of value types in C++ for examples of how to create a range-checked value type in C++.

Executive summary: Use a template to create a value type that has built-in minimum and maximum values, which you can use like this:

```<code>// create a float named 'percent' that's limited to the range 0..100
RangeCheckedValue<float, 0, 100> percent(50.0);
</code>```

You don't really even need a template here; you could use a class to similar effect. Using a template lets you specify the underlying type. Also, it's important to note that the type of percent above won't be a float, but rather an instance of the template. This may not satisfy the 'simple types' aspect of your question.

It's strange that this feature hasn't been added to languages.

Simple types are just that -- simple. They're often best used as the building blocks for creating the tools you need instead of being used directly.

Body:
See Limiting range of value types in C++ for examples of how to create a range-checked value type in C++.

Executive summary: Use a template to create a value type that has built-in minimum and maximum values, which you can use like this:

// create a float named 'percent' that's limited to the range 0..100
RangeCheckedValue<float, 0, 100> percent(50.0);

You don't really even need a template here; you could use a class to similar effect. Using a template lets you specify the underlying type. Also, it's important to note that the type of percent above won't be a float, but rather an instance of the template. This may not satisfy the 'simple types' aspect of your question.

It's strange that this feature hasn't been added to languages.

Simple types are just that -- simple. They're often best used as the building blocks for creating the tools you need instead of being used directly.


问:
Passing an object between different handlers or a Superclass that contains most of the logic
I'm going to try to make this as concise and concrete as possible, but apologies since I can think of multiple ways to make it work.  This question might also relate to handling production workflows or manufacturing, but I have no experience in these areas.

I have a problem where I need to move an Object, O, from different states to other states (like a Nondeterministic finite automata). The problem is the Object can be in different states at the same time, and the interaction sometimes matters.

For example say there are 10 states, O can be in up to 3 of those states at the same time. I'm a bit lost as to what type of code design I should use to model this.  The two ideas I am thinking about are

Pass O from handler to handler, and manage the transitions between states, and keep some sort of info in O saying which states they are in, so that each state can figure out what to do based on what other states O is in.

Have a larger Superclass that handles which states O is in, and handles the interactions.

I'd normally say 1. but handling all the interactions between handlers in each handler sounds messy.

What would be the better option between these 2? Or is there another method that is preferred?

** Update and Clarification **

As a concrete example. The Object can be in one of many physical locations, while it can also be in one of several stages of processing (The object might move back and forth between locations, or back and forth between the stages of processing). As additional complexity each physical location might have sublocations, but I think I can ignore that for now.  So if it's clearer, it can be considered to be two independent automata, but choosing the edge to move to the next state in either automata depends on it's state from both automata.

答:
2. Have a larger Superclass that handles which states O is in, and handles the interactions.

That sounds like an awful lot of logic from what you are describing. Do you want the same class defining that 30% complete parts in Atlanta have to be shipped to Dallas as the class that handles 99% complete parts in the East part of Dallas can be moved to finished in the same area?

Pass O from handler to handler, and manage the transitions between states, and keep some sort of info in O saying which states they are in, so that each state can figure out what to do based on what other states O is in.

I think this would be manageable if you provide a way to ignore the states you don't care about. If step 2 of assembly is always followed by step 3, regardless of location, you want to be able to return "go to step 3" without worrying about what factory you are in.

For instance you could make a wrapper class that allows partial transitions. If you are going the immutable route, the functions could return the result of the partial transition function, i.e.

```<code>if state.Production = Step.Two then
    return state.AlterProduction(Step.Three)
</code>```

Or you could go the mutable route and just transform the state with any updates.

Body:
2. Have a larger Superclass that handles which states O is in, and handles the interactions.

That sounds like an awful lot of logic from what you are describing. Do you want the same class defining that 30% complete parts in Atlanta have to be shipped to Dallas as the class that handles 99% complete parts in the East part of Dallas can be moved to finished in the same area?

Pass O from handler to handler, and manage the transitions between states, and keep some sort of info in O saying which states they are in, so that each state can figure out what to do based on what other states O is in.

I think this would be manageable if you provide a way to ignore the states you don't care about. If step 2 of assembly is always followed by step 3, regardless of location, you want to be able to return "go to step 3" without worrying about what factory you are in.

For instance you could make a wrapper class that allows partial transitions. If you are going the immutable route, the functions could return the result of the partial transition function, i.e.

if state.Production = Step.Two then
    return state.AlterProduction(Step.Three)

Or you could go the mutable route and just transform the state with any updates.


问:
Anonymous function performance - setTimeout
According to Gregory Baker & Erik Arvidsson (Google), creating a named function and then passing that to setTimeout is actually faster than creating an anonymous function (reference: Optimizing JavaScript code -> Avoiding pitfalls with closures):

Creating a closure is significantly slower then creating an inner function without a closure, and much slower than reusing a static function. For example:

<snip>

```<code>    function alertMsg() {
      var msg = 'Message to alert';
      alert(msg);
    }
</code>```

is slower than:

```<code>    function setupAlertTimeout() {
      window.setTimeout(alertMsg, 100);
    }
</code>```

In my testing, there does not appear to be any significant difference (jsPerf here), so why do they claim that creating a whole named function is faster than simply making an anonymous function?

EDIT: note that I am specifically referring to the last two examples, the first one has been removed for clarity.

答:
There is a significant difference in performance between your examples, but due to the speed of current JavaScript parsers, the difference isn't noticeable unless you're doing the call millions of times.

Therefore, this technique would be considered a micro-optimization, much like the technique of scoping variables to reduce prototype-chain lookups.  It may not make a difference if you do it 10 times in your jQuery event handlers, but it will make a significant and important difference when developing JavaScript Rendering Engines or when performing expensive operations on CPU-constrained systems.

Please check out the updated jsperf test at http://jsperf.com/closure-no-closure/2.


问:
Attachment handling for web application with Jackrabbit
I need to manage attachments on my Spring web application and I thought to use an open source repository.

My app it's a job approval system using J2EE / SPRING 3 Framework and Postgress DB to allow user to tracks the job,right through every step of the approval process.

It is a fully managed, collaborative system that operates from a central server and is accessed by a standard internet browser.

An user should be able to add an attach to a request or an approval step, so, I though to use Jackrabbit with Postgres database persistence manager.

I took a look to this post: http://onjava.com/pub/a/onjava/2006/10/04/what-is-java-content-repository.html?page=1

It's really interesting but, I've some question about this kind of solution :-

I seen that Jackrabbit standalone as a Derby database embedded solution for persistence, is it enough for a professional use of the repository with more than 50 request / days (with attachment) ?

Is there a reason for which I should use another database manager for persistence instead of the default one ?

答:
When you choose the database for repository you should base your decision on the same criteria like choose the database for web application. For instance, respond yourself to question: if derby is good for jackrabbit, why not use derby as a database for web application.

From this point of view I recommend to use the same database for both. This also give you advantages for maintenance, you will need to know only one database and don't need to duplicate maintenance scripts.

I suggest to use a database with table spaces. Data for web application and attachment to be store in different table spaces for optimization. Even you can have one database for both web application and jackrabbit with different schema and table spaces. More you can use the same database connection of JEE container.

Do you need one commit for both (web application and jackrabbit) known as 2 phase commit? If yes I know spring can do it, but I can't help you with that because I didn't work with spring.


问:
May I keep my program closed source if I link it against a static library of which the source is GNU GPLv2?
I'm putting much work in my program and after it's done I want to just setup a small website and sell each copy of the program but I don't want any legal issues.

Do I have to look for another library or can I "safely" link to it?

答:
No. You can't. That's a violation of the GPL and one can be sued for distributing software that uses the GPL'd library without making the source code of said library publicly available. The code that was freely given to the world came with the string that if you use it in a project, you have to freely give the project away. This is not the MIT or BSD open licenses, you can't take the code and lock it away under your own ownership. The people making this software did not do it to help you make a buck, they did it to help the world solve problems. </p>

<p>Go look for an alternative, or give it all away for free. </p>

Body:
No. You can't. That's a violation of the GPL and one can be sued for distributing software that uses the GPL'd library without making the source code of said library publicly available. The code that was freely given to the world came with the string that if you use it in a project, you have to freely give the project away. This is not the MIT or BSD open licenses, you can't take the code and lock it away under your own ownership. The people making this software did not do it to help you make a buck, they did it to help the world solve problems.

Go look for an alternative, or give it all away for free.


答:
The GPL is a heavily viral license.  If you use GPL code in your program at all, the entire codebase has to be compatible with the GPL.

If the library in question is available as both GPL and LGPL, you can link to it dynamically (as an external DLL/SO/dylib/whatever) without being in violation of the LGPL.  If not, you need to look for another library, or a different business model.

Title: May I keep my program closed source if I link it against a static library of which the source is GNU GPLv2?

Body:
I'm putting much work in my program and after it's done I want to just setup a small website and sell each copy of the program but I don't want any legal issues.

Do I have to look for another library or can I "safely" link to it?


问:
Are there efforts to build a collaboratively edited HTML/JS/DOM reference?
W3Schools has a reputation of being incomplete, sometimes incorrect, and ridden with advertising; still, when looking to look up some things or link to documentation when answering a SO question, it still is the only handy cross-browser resource.

There are other resources like the Mozilla Developer Network that is doing an increasingly great job documenting JavaScript, and the legendary and great Quirksmode. But they, as brilliant as they are, cover only parts of the areas I am talking about, and provide no community editing and quality control options.

Is anybody aware of efforts to create a collaboratively edited, cross-browser HTML/CSS/JavaScript/DOM encyclopedia? If you will, I'm thinking of a challenger to W3Schools like SO was to Experts Exchange.

答:
WebPlatform.org sounds like what you want.

Web Platform is an open community of developers building resources for a better web, regardless of brand, browser or platform. Anyone can contribute to the reference, by collaborating in the wiki documentation pages, asking and answering questions in the Q&A forum, sharing and commenting on the WebPlatform blog posts, and communicating through the IRC chat channel.

WebPlatform was convened by W3C, that is seeking to create an online reference of Web standards. The project is a collaboration among Adobe, Apple, Facebook, Google, HP, Microsoft, Mozilla, Nokia, Opera, and W3C. There are currently efforts under-way to migrate the data from sources like MDN into WebPlatform.


答:
I agree with what @bigtang was saying. But more specifically, put some time aside to think instead of learn. Try to produce an idea that excites you. A program or a lyric or a topic. Once you have an idea and are excited, you'll want to start making. You won't be able to resist making.

Of course, then you will run problems while making and learn from them. And hopefully that will be more fun than just reading.

p.s.

be careful with @Pierre 303's suggestion. don't run out and spend hours reading those books. a chapter, sure, but you need to focus on making, and try to not put it off by learning about how to not put it off.

Title: Ship Early, Ship Never


答:
Ada also is a language that allows limits for simple types, in fact in Ada it's good practice to define your own types for your program to guarantee correctness.

```<code>type MyType1   is range    1 .. 100;
type MyType2   is range    5 .. 15;

myVar1 : MyType1;
</code>```

It was used for a long time by the DoD, maybe still is but I've lost track of it's current use.

Body:
Ada also is a language that allows limits for simple types, in fact in Ada it's good practice to define your own types for your program to guarantee correctness.

type MyType1   is range    1 .. 100;
type MyType2   is range    5 .. 15;

myVar1 : MyType1;

It was used for a long time by the DoD, maybe still is but I've lost track of it's current use.


问:
Controller JSP - no view
Most people say do not use JSPs. But what if I have a JSP that does not show anything, it only acts as a controller? Why would I do that? Because we do not need to redeploy complete webapp to make a small but significant change in a servlet -> instead can just put my new JSP in the JBoss tmp folder till we do a full deploy.

This controller JSP will of course include / redirect to other view JSPs for final rendering.

Question what are the downsides of doing this? If we already have it in our application (it's been working for the last 8 years before I joined); should we keep it as it works or are there any compelling reasons to change it to a regular servlet?

Note: the JSPs in question are not the only controller, rather they do some of the processing for certain use cases

答:
Having a jsp as a controller is wrong for multiple reasons. Development mode should not dictate application architecture or in other words if you need hot deploy choose a proper tool/server for that. Adding an intermediate controller (jsp) create many data handling problems than it solves. For instance how do you handle passing request parameters? How do you handling error validation? Can you keep the user to initial page if there were validation errors? This are just a couple of issues that comes immediately.

Now, for your real problem, actually you don't need the controller jsp. You said you use jboss, on jboss you can deploy an application exploded. In that case if you overwrite a jsp with a new version (copy from development directory) and refresh the view the page is displayed based on the last version. You can have hot reload also for java classes but for that you need a special tool. Take a look on this question Which Java web frameworks provide hot-reload?

Title: Controller JSP - no view


问:
Designing a universal database driver class
I have a homebrew MVC framework that I have been using for a while, and it has been working great, but I am planning an upgrade to it for its ORM classes. So far, it only supports SQL databases by creating statements dependent on what function is being called. The ORM class includes field structure and validation, computed fields, indices and joined classes (for associations, 1-1, 1-*, *-1 and *-*), and that provides enough functionality for selecting any data and fetching associated rows in the database.

But I would like to extend it to support XML, LDAP and NoSQL databases (i.e. MongoDB). My ideas for implementing this would be to modify the functions within the ORM class to interact with a custom driver (for each database type) in a common format. Unfortunately, I haven't had enough experience with using these other formats enough to adequately design an interface class that could be used by the ORM for any type.

So, are there any universal database drivers that would support all of these database types so I can learn by example?

The current interface I am working by is:

```<code>interface DBDriver {
  function connect($host, $un, $pw, $persist = false);
  function disconnect();
  function selectDB($db);
  function charset($charset);
  function insert($table, $values);
  function select($table, $fields, $joins, $where, $group, $having, $order, $limit);
  function update($table, $where, $values, $where, $order, $limit);
  function delete($table, $where, $order, $limit);
  function transactionBegin();
  function transactionCommit();
  function transactionRollback();
}
</code>```

But I am concerned that although this will provide enough for creating SQL statements, it might not be sufficient, or perhaps even overkill for other methods such as XML or NoSQL.

答:
It would be so abstract that it wouldn't do anything useful (analysis paralysis / abstraction inaction). The best thing to do would be to define interfaces for CRUD/BREAD/etc and implement them as they are needed. If you're using PHP 5.4 you can take advantage of traits so you can cook up drivers piecemeal for shared behavior.</p>

```<code>interface Create { }
interface Read { }
interface Update { }
interface Delete { }
interface Browse { }
interface Edit { }
interface Add { }
interface CRUD extends Create, Read, Update, Delete { }
interface BREAD extends Browse, Read, Edit, Add, Delete { }
interface Transactional { }
</code>```

Body:
It would be so abstract that it wouldn't do anything useful (analysis paralysis / abstraction inaction). The best thing to do would be to define interfaces for CRUD/BREAD/etc and implement them as they are needed. If you're using PHP 5.4 you can take advantage of traits so you can cook up drivers piecemeal for shared behavior.

interface Create { }
interface Read { }
interface Update { }
interface Delete { }
interface Browse { }
interface Edit { }
interface Add { }
interface CRUD extends Create, Read, Update, Delete { }
interface BREAD extends Browse, Read, Edit, Add, Delete { }
interface Transactional { }


答:
Seperation of concerns and divide/conquer approaches can be another explaination for this questions. Seperation of concerns gives the ability of portability and in some more complex architectures, it gives the platform independent scaling and performance advantages.

In this context, if you think about a 5-tiered archictecture (client,presentation,bussiness,integration and resource tier) lower level of architecture shouldn't be aware of the logic and bussiness of the higher levels and vice versa. I mean by lower level as integration and resource levels. Database integration interfaces provided in integration and real database and webservices (3rd party data providers) belongs to resource tier. So that suppose you will change your MySQL database to a NoSQL document DB like MangoDB in terms of scalability or whatever.

In this approach, bussiness tier doesn't care how the integration tier provides the connection/transmission by the resource. It only looks for data access objects provided by the integration tier. This could be expanded to more scenarios but basically, seperation of concerns could be the number one reason for this.

Title: Why is it a good idea for "lower" application layers not to be aware of "higher" ones?

Body:
In a typical (well-designed) MVC web app, the database is not aware of the model code, the model code is not aware of the controller code, and the controller code is not aware of the view code. (I imagine you could even start as far down as the hardware, or perhaps even further, and the pattern might be the same.)

Going the other direction, you can go just one layer down. The view can be aware of the controller but not the model; the controller can be aware of the model but not the database; the model can be aware of the database but not the OS. (Anything deeper is probably irrelevant.)

I can intuitively grasp why this is a good idea but I can't articulate it. Why is this unidirectional style of layering a good idea?


问:
Possible with PHP MVC Framework? A better solution to client 'override' of core functionality?
Background / The Problem

I need to make a (large) application with a certain set of core functionality, and certain functionality for multiple clients within it. Each client has different requirements and while they may share some functionality, I need to separate the code for each client, so a change to one won't affect others. Each client section of the application should also inherit some features from the core application. Ideally I would like to separate the databases for each client too. In terms of a user system, core users should be able to have access to each client's functionality, but client users should only be able to interact with their specific client section of the site.

Current Solution

Each client has its own subdomain and the MVC can override the core's MVC files IF they exist. In a nutshell, my custom MVC's autoloader checks the client directory for the matching M,V, or C file when a subdomain is present in the URL and loads that particular client's file INSTEAD OF the core file. It's an override ability in a sense.

Questions

Am I solving this problem in a way that would be considered good practice in terms of software design?

If I were to use an existing PHP Framework (I would like to), how might I go about setting it up to solve this problem? Specifically I have been looking at Yii and CodeIgniter.

Thanks in advance!

Update:
I have discovered a design pattern called HMVC (Hierarchical MVC) and it seems to be essentially what I have described. I see that Kohana 3 is built using it and that Codeigniter has an extension that allows it.

答:
What you want is a form of dependency injection.

Try symbolic classes:

```<code>namespace Core;
class X { }
class Y { }
</code>```

```<code>namespace MrSmith\Core;
class X extends \Core\X { } // extend specific core class for Mr. Smith
</code>```

```<code>define('CLIENT_NAME','MrSmith');
$x = new \Sym\Core\X();
$y = new \Sym\Core\Y();
</code>```

Have the autoloader see "Sym" in the namespace and load \MrSmith\Core\X and then alias it with \Sym\Core\X.

Then it attempts the same with \Sym\Core\Y, can't find one for Mr. Smith, and falls back to \Core\Y.

This way you only need to define deviations on a per-client basis, with each client in their own sandbox.

If you're deploying the system by giving each client a copy and they're sandboxed already in their own subdomain/document root, you could skip using CLIENT_NAME and just have it look in a "Sym" directory, and use "Sym" as the namespace instead of "MrSmith".

Body:
What you want is a form of dependency injection.

Try symbolic classes:

namespace Core;
class X { }
class Y { }

namespace MrSmith\Core;
class X extends \Core\X { } // extend specific core class for Mr. Smith

define('CLIENT_NAME','MrSmith');
$x = new \Sym\Core\X();
$y = new \Sym\Core\Y();

Have the autoloader see "Sym" in the namespace and load \MrSmith\Core\X and then alias it with \Sym\Core\X.

Then it attempts the same with \Sym\Core\Y, can't find one for Mr. Smith, and falls back to \Core\Y.

This way you only need to define deviations on a per-client basis, with each client in their own sandbox.

If you're deploying the system by giving each client a copy and they're sandboxed already in their own subdomain/document root, you could skip using CLIENT_NAME and just have it look in a "Sym" directory, and use "Sym" as the namespace instead of "MrSmith".