text:
Object Oriented Programming/Introduction To OOP

= Introduction = For an overview and history of Object Oriented programming OOP, please reference the Wikipedia article.

The reader is expected to have a basic familiarity with programming in general, as we will give examples in a variety of languages. We will explain any non-obvious syntax in the discussion, although this is beside the point. The point is to give some indication of the flavor of the languages and some insight into the real-world application of OO ideas.

Overview
We will divide up OOP into two phases— classic and modern. While this distinction is somewhat arbitrary, we believe it is instructive to consider OOP as it was practiced in the 1980s and early 1990s to demonstrate the motivation for more current practices.

What is Classic OOP?

Object oriented programming can be traced back to a language called Simula, and in particular Simula 67, which was popular during the 1960s. It was Simula that first instituted "classes" and "objects," leading to the term "object oriented" programming. By the early 1990s, enough experience had been gained with large OOP projects to discover some limitations. Languages such as Self, ideas like interface programming (also known as component or component-oriented programming), and methodologies such as generic programming were being developed in response to these difficulties. Although often derided by OOP purists, it was the standardization of C++ in 1998 —including generic programming facilities — that really ushered in the modern era of OOP, which we also refer to as Multi-Paradigm programming. This is largely due to the popularity of C++ and the genius of the Standard Template Library (STL) demonstrating the utility of the new methodology to such a large audience.

Classic or Pure OOP
By 1980, Xerox had made Smalltalk available to outsiders, appropriately named Smalltalk-80. Unlike other early programming languages, Smalltalk was a complete environment rather than just a language, a characteristic it had in common with Lisp at the time. While Lisp machines were foreshadowing IDEs to come, Smalltalk was pioneering the GUI, ultimately influencing the development of the Macintosh computer. Meanwhile, while Xerox was developing Smalltalk during the 70s, the C language was becoming popular thanks to UNIX being largely written in C. Therefore, it was C —an otherwise unlikely candidate —that Bjarne Stroustrup fused with ideas from Simula to create "C with Classes" which was renamed to C++ in 1983. In 1985, unsatisfied with Smalltalk, C++, and various object systems being tacked onto Lisp dialects, Bertrand Meyer created Eiffel. Even though much more recent, Java essentially cloned vintage C++, and so we consider Smalltalk, vintage C++, Eiffel, and Java to be Classic OOP. The object systems tacked onto Lisp (eventually standardized as CLOS in 1994) produced a very different methodology. While we don't consider CLOS to be Classic OOP, it did influence modern OOP.

Modern OOP and Multi Paradigm Programming
Classic OOP developed a tendency to over-rely on a technique called "inheritance," and eventually programmers realized that they were using inheritance for many things that are conceptually distinct. Modern OOP basically incorporates these concepts, sometimes as language level features, sometimes through programmer practice. The goal largely being looser coupling, easier maintenance and reuse. Historically, David Ungar and Randall Smith completed their first working Self compiler in 1987, and by 1990 Sun Microsystems had picked up the project. While Self did not survive to really become a modern OOP language, it was a second generation OOP language. Then, in the early 1990s, Alexander Stepanov and Meng Lee pioneered generic programming and wrote early drafts of C++'s STL. This began a (still ongoing) trend of incorporating functional programming ideas into more traditional OOP environments, in a kind of reverse CLOS. Additionally, the early 1990s saw the development of CORBA and Microsoft's COM, which was a natural extension of the ideas that had led to the original Windows API. This interface or component programming was a natural extension of encapsulation —a basic tenet of OOP, as we will see. All of these developments were aimed at further managing or reducing complexity. Since this was the original goal of OOP and these techniques are used in conjunction with classic OOP, we find it appropriate to consider them in a treatment on "OOP".

Contemporary object oriented programming, therefore, tends to be rather distinct from classic object oriented programming. Particularly, getting used to which abstractions are the most useful for which problem types is more challenging now that there are more from which to choose! In a now classic book, Gamma et. al. introduced Design Patterns which helped to synthesize a variety of OOP techniques as applied to very common problems.

Future of OOP
The future contains more standardization of functional programming techniques in OOP environments, particularly lambda expressions and closures, and more robust meta-programming constructs. Applying design patterns automatically through generic or meta programming techniques is an interesting area.

What is an Object?
Loosely, the term object is used to conjure up connections with real world objects like a chair or a guitar. Except that for software, only some simplified abstraction is used, designed specifically for the task at hand. While a real chair is composed of atoms and molecules and reacts to its environment based on the laws of physics and its atomic composition, a "chair object" will vary wildly depending on whether you're writing a game or a Point-of-Sale system for a furniture store. Approaching your problem from the perspective of the chair will not be as productive as approaching the chair from the perspective of your problem.

In most of the languages used in this book, you will find that technically speaking (something akin to whistling 9600 baud, I understand), an object is "an instance of a class". Great, so what does that mean? Well, we can trace this idea all the way back to Plato and his Platonic Ideal. If you spent more time watching Bill and Ted's Excellent Adventure than reading Plato, the idea is that the concept of a chair is a separate entity from any particular chair. In other words, you can conceive of a chair in the abstract without thinking of any particular chair.

In most OOP languages, this abstracted idea of a chair is called a class (from classification) and is a prototype or blueprint for actually making chairs. The act of making something from the blueprint is often called instantiating, and the made thing is both an object and an instance of the class that served as a blueprint. As humans, we normally tend to do this in reverse —we categorize objects we encounter. We can easily identify chair-like things we run into as being chairs; this classification is where we got the term class in the first place.

It is easy to drift off into abstruse philosophical debates over objectness; in some areas like knowledge representation and computational ontology they are very relevant. However, for a computer programmer, it is only necessary to figure out what your application needs to know about and do with chairs. This can be a sufficiently difficult problem, it's usually not necessary to make it harder!

If you're still fuzzy on the whole idea, consider a more technical explanation. Structs (structures), records, tables, and other ways of organizing related information predated object oriented programming. You may be familiar with something like the following Pascal code:

This doesn't actually create a chair variable, but defines what a chair variable will look like when you create one. You could proceed to create arrays of chairs and so forth, and as we hope you've discovered for yourself, this kind of thing is quite indispensable for keeping your programs understandable. Object oriented programming wants to push this advantage and milk it for every ounce of understandability, correctness, and simplicity it can.

A fundamental problem solving technique is divide and conquer —you just have to figure out how to partition your problem into sub-problems. OOP innovators realized that we already had figured out ways to partition the problem, and it was reflected in the way we organized our data, like above. If you looked at an application that had that chair RECORD in it, you would surely find lots of code for doing things with chairs. Why else would you bother to define it? So, if you were to extract all of that code from all over the application and put it together with the chair definition, the reasoning goes, you should have an easier time ensuring that:

  all chair code is correct   all chair code is consistent with each other   there's no duplicated chair code   overall, you have less spaghetti because chair code is no longer tangled up with sofa code etc

So you take that chair definition and that code extracted from all over the application, and call that a class. Take a chair variable and call it an object, and you're off to the races.

Since this is supposed to be a pragmatic book, let's look at our first example code, this time in Python code:

This doesn't look terribly different from the Pascal example. The only difference is that class Chair now contains a has_arms method. Methods are functions that live within a class, and are usually used to process certain class specific data. Hopefully the purpose is fairly clear, so let me point out the important part: has_arms is a calculated or inferred property—this information is not stored directly.

In Python, you would use this class like so:

Here, the "c" variable is an instance of the 'chair' Class, also known as a chair object. We initialize the properties like you would in Pascal (this will change later!) and do one thing if the chair has arms and something else if it doesn't. But we never initialized a "has_arms" property or anything of the like.

Since part of the goal is for you to become syntax agnostic, we present this same example again in C++:

Now, we would just like to mention that this is just the tip of the iceberg and this example is not representative of good style (in either language). There may seem like little purpose to making objects with so little functionality, and you could easily generate equivalent code that requires no new class:

The purpose of this section is to help you understand the terms; we will delve more into the benefits in the sections on encapsulation, polymorphism, inheritance, and on and on. However, let us say that while the "low-level" way might seem shorter and simpler, the object oriented benefits accrue with program size and complexity. This is not surprising, as that's what OOP was designed for, but it does make simple examples hard to come by. So bear with us.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text: Category:Book:Object Oriented Programming


text:
Wikijunior:Asia/Taiwan

Taiwan (traditional Chinese: 臺灣/台灣; simplified Chinese: 台湾), officially the Republic of China (ROC), is an island in Eastern Asia.

Taiwan's beginnings track back to the 15th century, where European sailors passing by recorded the island’s name as Ilha Formosa ("beautiful island"). In 1624, the Dutch East India Company established a base in southwestern Taiwan, going from aboriginal grain production practices and employing Chinese laborers to working on rice and sugar plantations. In 1683, the Qing Dynasty (1644-1912) forces take control of Taiwan’s western and northern coastal areas and declared Taiwan as a province of the Qing Empire in 1885. In 1895, after being defeated in the First Sino-Japanese War (1894-1895), the Qing government signed the Treaty of Shimonoseki, handing over Taiwan's sovereignty to Japan, who ruled the country until 1945.

Taipei is the capital city of Taiwan and New Taiwan Dollar (NT$) is the currency of Taiwan.

Where is Taiwan?
Taiwan is in the Philippine Sea, neighboring China towards the west, Japan towards the northeast and the Philippines to the south.

How many people live in Taiwan?
Based on last national census in 2010, the population of Taiwan is estimated at 23.12 million peoples. The natives identifies themselves as Taiwanese. The population of Taiwan is composed of these ethnic or sub-ethnic groups: Groups of the Fukien Taiwanese (Fukienese [Fujianese], or Hoklo) and the Hakka (84%) and Chinese who came from mainland China (14%), aboriginal peoples (2.0%). The aboriginal people consists of sub-ethnic group such as: Amis, Atayal, Paiwan, Bunun, Rukai, Puyuma, Tsou, Saisiyat , Truku and Sediq.

What are the most common languages in Taiwan?
According to Taiwan National Census 2010, large majority of populations (83.5%) in Taiwan speak Mandarin (a.k.a Putonghua). Concurrently, 81,9% of population, also speaks a special dialect of Chinese known as the Taiwanese Hokkien / Minan. It is the most common language used among the population and can be seen and heard all over in public. The language form is of Southern Min (often called Taiwanese on Taiwan), which comes from southern Fukien province. 6.6% speaks Hakka and 1.4% speak indigenous languages.

Taiwanese Mandarin is the official language in Taiwan. It serves as the lingua franca of the country. While the vocabulary of the Mandarin spoken in Taiwan is still modern, the country uses the Traditional Chinese characters to write the language. This is in contrast to mainland China, which has adopted a simplified way of writing the characters (known as Simplified Chinese characters).

The mainlanders speak Mandarin Chinese, the official language of China. Most aboriginal people speak Mandarin; many speak Taiwanese, and a small number of people (mostly elders) speak Japanese. Hoklos also speak Mandarin. Most Hakka speak Taiwanese and Mandarin.

What is the most common religion in Taiwan?
The Aboriginal peoples practice animism, nature worship, and other Indigenous religious rites (18.2%). The Chinese brought Buddhism (35.3%), Daoism (Taoism) (33.2%), and Confucianism to Taiwan. The Dutch introduced Protestant Christianity and the Spanish Roman Catholicism (3.9%). The Japanese brought Shinto (9.4%). In 1949, many religious groups and religious leaders—especially Confucian, Buddhist, and Daoist—fled to Taiwan from China.

What is the sport of Taiwan?
The most popular sport in Taiwan by far is baseball.

It was introduced to Taiwan by Japan after China ceded control of the island to Japan in 1895. Initially played only by Japanese colonial administrators, by the 1920s interest in the sport spread across the island with games between Taiwanese natives and Japanese immigrants becoming common

Over the decades, the local Taiwanese honed their own techniques and some of the talented players are exported to USA, Japan and South Korea.

What are some important sites?
The Taiwan is a very interesting places with there are many things to see and do in Taiwan.

Fort Santo Domingo - Fort Santo Domingo was built in 1629 by the Spanish, although the site has been home to both Dutch and British since. Situated in Xinbei, the fort has been altered by both the Dutch and British, who constructed stone walls and added the British Consulate.

Taipei 101 - Finished construction in 2004, it was once the world's tallest skyscrapper. It is located in the Xinyi District of Taipei, an area known for its financial services and vibrant shopping malls. One of the more famous attractions is a 728-ton tuned mass damper (TMD), a large spherical steel pendulum that offsets lateral movements caused by strong winds.

Yehliu Geopark - It is on Taiwan’s north coast cape in Wanli, near Keelung City, famous for its hoodoo stones, thin spires of rock formed by sedimentary stone. Many rock formations have creative names, including the most well-known “The Queen's Head.”

Night markets - Night Markets is initially began as informal vendor meetings, where merchants would get together and sell their wares. It is a local Taiwanese culture where the usually empty streets at day time will be filled with the vendors selling all sorts of goods during evening time. One of the more famous and largest night market in Taiwan is Shilin night market Hot Springs - There are many hot springs that are located in Taiwan due to its proximity location near the Ring of Fire, one of the more famous one is Beitou Hot Spring

Whale Cave - It is a natural basalt sea cave on the north side of Hsiaomen Island in Penghu, and one of the many tourist attractions in the area. According to some it looks like a whale, but that is not the true origin of its name. The actual reason for the cave's name "Whale Cave" is that, a long time ago, a whale got stuck in the cave and died. According to local legend, a bone from that whale is now inside Dayi Temple located near to the Whale Cave.

Sun Moon Lake - It is Taiwan's largest lake Taiwan's largest lake,and located in the mountains of Nantou at the geographic centre of Taiwan island. The name of the lake is inspired by the beauty of the area. The east side of the lake is round, like the sun, while the west side is long and narrow, like a crescent moon.

Cijin Wind Turbine Park - There are some wind turbines that are built there with purpose of generating electricity for the park lights.

title: Wikijunior:Asia/Taiwan


text:
Object Oriented Programming/Classes, Types, and Classic OOP

Classes, Types, and Classic OOP
There are some books on OOP that will tell you that the cornerstones of object oriented programming are encapsulation, inheritance, and polymorphism, or something along those lines. This is fairly typical of the classic OOP view, and there's nothing wrong with it per-se, it's just that we've generalized some ideas and decoupled things here and there since then.

Simple Objects vs Behavioral Entities
There are two fundamentally different types of objects, created and designed with different purposes in mind, using different techniques. We label these two types "Simple Objects" and "Behavioral Entities," although these labels are our own. Simple objects tend to represent values, like colors, coordinates, vectors, strings, etc, while behavioral entities tend to represent system components like services, message queues, engines, application logic, etc.  Simple objects, if they own anything, are just wrapping what they own (like a system level handle). Usually, however, simple objects are untied to anything else, have no complicated startup or shutdown, and have little overhead. Simple objects tend to demand high performance, guaranteed correctness, discourage incorrect usage, are put in collections, searched, passed around, and generally manipulated by the rest of the program. Writing good simple objects, combined with good collection libraries provided by your language of choice, can easily reduce the complexity of basic operations by as much as 80%. Simple objects tend to focus on the encapsulation side of OOP rather than fancy message passing, as it's usually not a helpful abstraction to think of simple objects sending or receiving messages.  Behavioral entities tend to maintain their state in various collections of simple objects, like a server keeping a list of logged in users. Behavioral entities tend to focus on behavior (to state the obvious), and configuring or tailoring that behavior in various circumstances. Message passing mechanisms, including polymorphism, tend to be central to the construction of behavioral entities. As a result, you tend to get whole families of similar entities, for example, an FTP server, an ssh server, an HTTP server, etc. that all have common functionality (like accepting connections).  One of the primary forces behind OOP is separating out all of the common elements from these families and writing it once. This has obvious advantages in debugging and maintenance: you only have to fix bugs in common code once. Obviously, this is just abstraction at work but OOP gives you a well understood set of tools to do it with. Some languages features are tailored for one or the other. For example, operator overloading is truly important for simple objects, but mostly irrelevant for behavioral entities.

Encapsulation
Encapsulation is about risk management, reducing your maintenance burden, and limiting your exposure to vulnerabilities —especially those caused by bypassed/forgotten sanity checks or initialization procedures, or various issues that may arise due to the simple fact of the code changing in different ways over time. Technically, encapsulation is hiding internal details behind an opaque barrier so as to force external entities to interact through publicly available access points.  Think about it in the context of an OS kernel, like the Linux kernel. In general, you don't want a common user level application modifying any internal kernel data structures directly —you want applications to work through the API (Application Programming Interface). Hence encapsulation is the general term we use for giving varied levels of separation between any core system elements and any common application elements. Otherwise, "unencapsulated code" would be bad for a number of obvious reasons:  Applications could easily set invalid or nonsensical values, causing the whole system to crash. Forcing the application to use the API ensures that sanity checks get run on all parameters and all data structures maintain a consistent state. Internal data structures could be updated and change (even drastically so) between seemingly minor kernel updates. Sticking to the API insulates application developers from having to rewrite their code all the time. Applications could be used to "snoop" on each other, elevate their privileges, hog system resources, and violate any number of security protocols if they could directly manipulate kernel data structures. Application developers need little or no understanding of the Linux kernel to access kernel data. The random number engine illustrates this well. It can be accessed through /dev/random instead of wading through kernel structures, and you still get the same data. There are more, surely you can think of some. You may be thinking, "This is supposed to be about object oriented programming. I don't want to be a kernel developer!" Yes, we know, but the software kernel is the perfect example for discussing encapsulation, even though the kernel possesses no object oriented code itself. Encapsulation does not strictly apply to OOP, but it is used most within it. All the kernel's internal data —its message queues, its process lists, its filehandles, etc. —are all encapsulated inside the kernel, and cannot be seen outside the kernel. To work with the kernel, you must use its public interface, the API. For all the same reasons, writing your code in this way pertains the same benefits, even for writing a small app like a text editor or a mail client.  Since the entire purpose of encapsulation is to hide details and restrict access, it makes us consider exactly how access is restricted. It also makes us consider what exactly is a detail that needs to be protected, and what exactly should be exposed to the outside world. Figuring out what to expose, and especially at what granularity, is something of an art and we'll talk about it more in the section on interfaces. We'll move on to access restrictions, which come in two basic kinds: compile time and run time.  Encapsulation is nothing but a combining of code and data as a single unit. It is achieved using the class concept, e.g.:  In the above example we are combining data (a and b) and the methods (read, print, cal) in to a single unit called by addition. Now we can access those methods by using objects.  Compile Time Enforced Access Restrictions Many OOP languages have keywords along the lines of "public", "private" and "protected". These three were used by C++ in particular and have been oft copied since. They are used to group class members into three different levels of access:  Public: Part of the public interface, anybody can access this member. Private: An internal detail, only members of this class may access this member. Protected: An internal detail also available to descendants of this class. As you can see, this is not the most flexible framework for controlling access. C++ also has a "friend" keyword to allow certain exceptions to access restrictions, but other problems persist. One common problem results from single classes that grow very large: sometimes you want access restricted to a subset of a classes functions. Alternatively, many generic frameworks like serialization or persistence need access to "private" data members. Unfortunately, there is no way to differentiate between "implementation detail" and "secret information".  These kinds of language-level keywords only serve to prevent programs that violate these restrictions from compiling (and most scripting languages are compiled to some intermediate form these days). If somebody used a modified compiler that ignored these access restrictions (or in some languages just used some casting tricks), there is generally nothing to prevent a determined programmer from getting around these barriers.  Runtime Enforced Access Restrictions Depending on the chip architecture in use, or possibly on the virtual machine running the byte code, it is sometimes possible to put "protected" information into areas of memory that will generate exceptions if read from, written to, or both. This allows for a program to abort or take other action if encapsulation is violated.  Accessors and Virtual (or Calculated) Properties Accessors are just functions that set or return properties of an object. All too often, you'll see this kind of code in Java:  In this case, getVal and setVal are accessors, or accessor functions. Java promotes lots of gratuitous accessors, and it often looks like unnecessary bloat. Sometimes it is. But often, people miss the point of encapsulation. If Dummy is well thought out, then Val is conceptually a property of Dummy. The fact that in this case that property is kept as a couple of bytes in memory is besides the point for anybody using a "Dummy". Even more importantly, users of Dummies are protected from any changes to how Val is calculated. All too often, the writer of a Dummy class is one himself, and Val has no logical or conceptual significance, and the accessors just get in the way.


text:
Object Oriented Programming/"State" is Evil!

"State" is Evil!
Something that we don't see reiterated enough: State (as opposed to change) is evil! Or, (perhaps better said) maintaining unnecessary state is the root of all (er... many) bugs. Let's look at an example, now in Ruby:

We're displaying something over time, so we're dealingwith both pixels and seconds. Based on the zoom level, there is a correlation between them: pixels per second, or PPS. In this example, we're maintaining gratuitous state — which is to say, we're holding the position in both seconds AND pixels. This is convenient, and important for users of this class, but we've messed up the encapsulation here. Whenever you set the value in one unit, you've destroyed the correctness for the other unit. Okay, you say, here's a simple fix:

This fixes the obvious error with the previous example, but you've created a lot of work for yourself. Now you have to keep every calculation in every method in the Timeline class duplicated to maintain consistency. There could be dozens more where this came from (trust me). And what about when you add in other units, say inches? You have to duplicate all of that again. Presumably, you see where this is heading: calculated properties, logical properties, virtual properties, whatever you like to call them. Let's see this example again: Now, we're presuming that the conversion factors of PPS and IPS are set correctly for simplicity, but otherwise we've vastly simplified our problem. In twenty other functions we now write, we only have to worry about seconds, there's no consistency problems to worry about. Additionally, if we need to change our base units from seconds to pixels, the Timeline users need never know.


text:
Object Oriented Programming/State is evil

"State" is Evil!
Something that we don't see reiterated enough: State (as opposed to change) is evil! Or, (perhaps better said) maintaining unnecessary state is the root of all (er... many) bugs. Let's look at an example, now in Ruby:

 * 1) We're displaying something over time, so we're dealing
 * 2) with both pixels and seconds.  Based on the zoom level,
 * 3) there is a correlation between them: pixels per second,
 * 4) or PPS.

Class Timeline { PPS; current_position_in_seconds; current_position_in_pixels; public:

GetPosInSeconds {current_position_in_seconds;} SetPosInSeconds(s) {current_position_in_seconds = s;} # oops, we're out of sync

GetPosInPixels {current_position_in_pixels;} SetPosInPixels(p) {current_position_in_pixels = p;} #oops, we're out of sync } In this example, we're maintaining gratuitous state — which is to say, we're holding the position in both seconds AND pixels. This is convenient, and important for users of this class, but we've messed up the encapsulation here. Whenever you set the value in one unit, you've destroyed the correctness for the other unit. Okay, you say, here's a simple fix:

 * 1) We're displaying something over time, so we're dealing
 * 2) with both pixels and seconds.  Based on the zoom level,
 * 3) there is a correlation between them: pixels per second,
 * 4) or PPS.

Class Timeline { PPS; current_position_in_seconds; current_position_in_pixels; public:

GetPosInSeconds {current_position_in_seconds;} SetPosInSeconds(s) {         current_position_in_seconds = s;          current_position_in_pixels = s*PPS; }

GetPosInPixels {current_position_in_pixels;} SetPosInPixels(p) {         current_position_in_pixels = p;          current_position_in_seconds = p/PPS; } } This fixes the obvious error with the previous example, but you've created a lot of work for yourself. Now you have to keep every calculation in every method in the Timeline class duplicated to maintain consistency. There could be dozens more where this came from (trust me). And what about when you add in other units, say inches? You have to duplicate all of that again. Presumably, you see where this is heading: calculated properties, logical properties, virtual properties, whatever you like to call them. Let's see this example again:

Class Timeline { PPS; # Pixels Per Second IPS; # Inches Per Second current_position_in_seconds; public:

GetPosInSeconds {current_position_in_seconds;} SetPosInSeconds(s) {current_position_in_seconds = s;} GetPosInPixels {current_position_in_seconds*PPS;} SetPosInPixels(p) {current_position_in_seconds = p/PPS; } GetPosInInches {current_position_in_seconds*IPS;} SetPosInInches(i) {current_position_in_seconds = i/IPS; } } Now, we're presuming that the conversion factors of PPS and IPS are set correctly for simplicity, but otherwise we've vastly simplified our problem. In twenty other functions we now write, we only have to worry about seconds, there's no consistency problems to worry about. Additionally, if we need to change our base units from seconds to pixels, the Timeline users need never know.