Understanding “The Loop” in WordPress

Loop

When discussing WordPress, and specifically the development of themes (or creating new page templates inside an existing theme) you inevitably will run up against “The Loop”. The Loop is the framework within which WordPress constructs the content for any given page that user visits, whether that be a static home page or a blog view showcasing recent posts, or anything in between. It may sound a bit complex, but really, it’s just a looping mechanism.

The Loop, at its simplest, is a looping structure just like any other in programming. It iterates through what amounts to a list of all of your site’s content, cycling through your posts or pages, and fetching the requested content from them. At its most complicated, you can run The Loop multiple times, fetch only certain items from certain categories, only items not in certain categories, those published within a date range, or with other particular identifying information.

Every page template within a WordPress theme will likely contain The Loop. It’s one way that the template can search for and acquire content from your pages and posts, which are stored in the database. Let’s take a look at some specifics:

A Basic Example of the Loop

<?php 
if ( have_posts() ) {
    while ( have_posts() ) {
        the_post(); 
        // Post Content here
    }
}
?>

You can see in the above example that it’s really a pretty straightforward setup. The entire thing starts with a conditional, with have_posts checking to ensure that there are, in fact, any posts to find. Then the loop happens – while there are still posts (again using have_posts), it iterates through the next post and calls up the_post – which refers to the one currently being iterated through.

Particular Queries

If your needs are more advanced than simply returning every post that there is on your website, you’ll need to limit your queries. This is where WP_Query comes into play.

Filtering by Category

In the below example, modified from an example in the Codex, we will query for posts that are in the category which has the id of 4. Then, you can see a sample of the contents of the loop itself. Here, we check for posts with a category ID of 4, then, within the .post div, we display the post’s title (linked to the post), the date of the post, the post’s content, and the post’s metadata.

<!-- Query for posts which are in category 4 -->
<?php $query = new WP_Query( array( 'cat' => 4 ) ); ?>

<!-- Begin The Loop -->
<?php if ( $query->have_posts() ) {
      while ( $query->have_posts() ) {
        $query->the_post(); ?>
        <div class="post">
            <!-- Display the Title as a link to the Post's permalink. -->
            <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>

            <!-- Display the date (November 16th, 2009 format) and a link to other posts by this posts author. -->
            <small><?php the_time( 'F jS, Y' ); ?> by <?php the_author_posts_link(); ?></small>

                         <!-- Display the post content -->
            <div class="entry">
                  <?php the_content(); ?>
            </div>

                        <!-- Display the post metadata -->
            <p class="postmetadata"><?php _e( 'Posted in' ); ?> <?php the_category( ', ' ); ?></p>
        </div> 
    }
}

The use of WP_Query can lead to some very customizable results. You can include posts of only one category, or several, or include all except for those from one category or another. You can search and return posts that contain a keyword, or locate posts by ID, use the post_type to show only data from pages, and more. If you want to learn in more depth about WP_Query, take a look at the WP_Query documentation.

Tip: You can get the ID number of a category in several ways. One easy way is to head over to “Posts”, then “Categories” in your WP-Admin. Right click on the desired category name in the list, and save the URL. Then paste it in a text editor or notepad somewhere and take a look. As an example, it might look something like this: http://example.com/wp-admin/term.php?taxonomy=category&tag_ID=4&post_type=post&wp_http_referer=%2Fwp-admin%2Fedit-tags.php%3Ftaxonomy%3Dcategory – you’re looking for the tag_ID number!

Filtering by Custom Field Values

The custom fields that are available in WordPress can be fantastically useful, and you may at times also need to filter posts by the values set in those as well. A simple task, but it’s worth showing for beginning WordPress developers (or those who haven’t delved far into custom templates or The Loop) to realize how customizable all of this is. Say that you have a custom field department and you’re looking for posts with the value marketing:

$query = new WP_Query( array('meta_key' => 'department', 'meta_value' => 'marketing') );

Understanding “The Loop”

The truely best way to understand The Loop is simply to use it. Use it to fetch your content in the templates you create for themes, or in the code that you customize in existing templates in existing themes. When you want to do something, filter for certain criteria, run The Loop again – check the The Loop documentation in the Codex, or hit up Google for ideas. The sky’s the limit!

This article was originally found here.

The Complete Guide to WordPress Performance Optimization

Ecommerce software stats by builtwith.com

WordPress can thank its simplicity and a low barrier to entry for this pervasiveness. It’s easy to set up, and requires next to no technical knowledge. Hosting for WordPress can be found for as little as a couple of dollars per month, and the basic setup takes just a half hour of clicking. Free themes for WordPress are galore, some with included WYSIWYG page builders.

Many look down on it, but in many ways we can thank WordPress for the growth of the internet and PHP, and many internet professionals have WP’s gentle learning curve to thank for their careers.

But this ease of entry comes at a cost. Plenty of websites that proudly wear the WordPress badge were not done by professionals but by the cheapest developers. And often, it shows. Professional look and professional performance were afterthoughts.

One of the main points of feedback the owner of an aspiring high-quality website will get from a grudging professional is that performance and a professional look and feel shouldn’t be afterthoughts. You can’t easily paint or stick them over a website. Professional websites should be premeditated.

lingscars.com

A famous UK used car dealer, Ling’s Cars, tried a unique way to make a kitsch marketing punchline. Unless you’re REALLY sure about what you’re doing, DO NOT try this at home.

And this starts with…

Choice of Hosting

Typically, new users will go with products that are on the low-cost side, with most of beginner-friendly bells and whistles. Considering the shady business practices by some big industry players in this arena, and the complaints and demands for site migration professionals coming from clients, this is a part of website setup that requires due attention.

We can divide WordPress hosting vendors into a few tiers.

Premium, WordPress-dedicated vendors like Kinsta whose plans start at $100 per month, or even higher-grade managed hosting like WordPress VIP by Automattic, may be worth their salt, but also may be out of reach for many website owners.

Medium tier FlywheelA2 hostingSiteground and Pantheon are among those considered reliable and performance oriented, offering acceptable speed and a managed hosting service for those more price-conscious. Users here may get a bit less hand-holding, but these services usually strike an acceptable balance between a solid setup, price, and options for more advanced users. Not to forget, there is Cloudways, which is a hybrid between VPS and managed hosting. Those with their audience in Europe may look into Pilvia, as it offers a performant server stack and is pretty affordable.

There’s an interesting survey of customer satisfaction with more prominent hosting vendors, published by Codeinwp.

For those of us not scared of the command line, there are VPS and dedicated-server vendors like Digital OceanVultrLinode, Amazon’s LightsailHetzner in Europe, and OVH. Hetzner is a German vendor known for its quality physical servers on offer, somewhat above the price of virtual servers, while OVH offers very cost-efficient virtual servers. For the price-conscious, OVH’s subsidiary Kimsufi in Europe and Canada also offers bargain physical dedicated servers, and Host US has very affordable virtual servers.

 

With managed hosting, things to look for are a good server stack, good CDN integration, and of course SSD storage. Guaranteed resources, like with A2, are a big plus. The next thing to look for is SSH-access. Tech-savvy users may profit from WP-CLI availability.

When choosing a VPS, the thing to look for is XEN or KVM virtualization over OpenVZ, because it mitigates the overselling of resources, helping guarantee that the resources you bought are really yours. It also provides better security.

Easy Engine is software that can make your entire VPS/WordPress installation a one-hour job.

Regarding the server stack, Nginx is preferred to Apache if we’re pursuing performance, and PHP 7 is a must. If we really need Apache, using Nginx as a reverse proxy is a plus, but this setup can get complex.

Tests performed give PHP 7 a big edge over the previous version. According to fasthosts.co.uk:

WordPress 4.1 executed 95% more requests per second on PHP 7 compared to PHP 5.6.

When choosing your hosting, be aware of negative experiences with some providers that have become notorious.

Software Considerations

Things that usually slow down WordPress websites are bulky, bloated front ends with a lot of static resources and database queries. These issues arise from the choice of theme (and its page builders, huge sliders, etc) — which not only slow down initial loading due to many requests and overall size, but often slow down the browser due to a lot of JavaScript, and stuff to render, making it unresponsive.

The golden rule here is: don’t use it unless there’s a good reason to.

This may seem like a rule coming from the mouth of Homer Simpson, but if you can skip any of the bells and whistles, do so. Be conservative. If you must add some shiny functionality or JS eye candy, always prefer those tailored and coded as specifically as possible for your exact need. If you’re a skilled coder, and the project justifies the effort, code it yourself with minimalism in mind.

Review all the plugins your website can’t live without — and remove the others.

And most importantly: back up your website before you begin pruning!

Data model

If you have a theme where you use a lot of custom posts or fields, be warned that a lot of these will slow down your database queries. Keep your data model as simple as possible, and if not, consider that WordPress’ original intended purpose was as a blogging engine. If you need a lot more than that, you may want to consider some of the MVC web frameworks out there that will give you greater control over your data model and the choice of database.

 

In WordPress we can build a rich custom data model by using custom post typescustom taxonomies and custom fields, but be conscious of performance and complexity costs.

If you know your way around the code, inspect your theme to find unnecessary database queries. Every individual database trip spends precious milliseconds in your TTFB, and megabytes of your server’s memory. Remember that secondary loops can be costly — so be warned when using widgets and plugins that show extra posts, like in sliders or widget areas. If you must use them, consider fetching all your posts in a single query, where it may otherwise slow down your website. There’s a GitHub repo for those not wanting to code from scratch.

Meta queries can be expensive

Using custom fields to fetch posts by some criteria can be a great tool to develop sophisticated things with WP. This is an example of a meta query, and here you can find some elaboration on its costs. Summary: post meta wasn’t built for filtering, taxonomies were.

get_post_meta is a function typically called to fetch custom fields, and it can be called with just the post ID as an argument, in which case it fetches all the post’s meta fields in an array, or it can have a custom field’s name as a second argument, in which case it returns just the specified field.

If using get_post_meta()for a certain post multiple times on a single page or request (for multiple custom fields), be aware that this won’t incur extra cost, because the first time this function is called, all the post meta gets cached.

Database hygiene

Installing and deleting various plugins, and changing different themes over the lifetime of your website, often clutters your database with a lot of data that isn’t needed. It’s completely possible to discover — upon inspecting why a WordPress website is sluggish, or why it won’t even load, due to exhausted server memory — that the database has grown to hundreds and hundreds of megabytes, or over a gigabyte, with no content that explains it.

wp-options is where a lot of orphaned data usually gets left behind. This includes, but is not limited to, various transients (this post warns of best practices regarding deletion of transients in plugins). Transients are a form of cache, but as with any other caching, if misused, it can do more harm than good. If your server environment provides it, wp-cli has a command set dedicated to transients management, including deletion. If not, there are plugins in the WordPress plugins repo that can delete expired transients, but which offer less control.

If deleting transients still leaves us with a bloated database without any tangible cause, WP-Sweep is an excellent free tool that can do the job of cleaning up the database. Another one to consider is WP Optimize.

Before doing any kind of database cleanup, it’s strongly recommended that you back up your database!

One of the plugins that comes in very handy for profiling of the whole WordPress request lifecycle is Debug Objects. It offers an inspection of all the transients, shortcodes, classes, styles and scripts, templates loaded, db queries, and hooks.

Debug Objects plugin output

After ensuring a sane, performance-oriented setup — considering our server stack in advance, eliminating the possible bloat created by theme choice and plugins and widgets overload — we should try to identify bottlenecks.

If we test our website in a tool like Pingdom Speed Test, we’ll get a waterfall chart of all the resources loaded in the request:

 

Pingdom Waterfall Chart

This gives us details about the request-response lifecycle, which we can analyze for bottlenecks. For instance:

  • If the pink DNS time above is too big, it could mean we should consider caching our DNS records for a longer period. This is done by increasing the TTL setting in our domain management/registrar dashboard.
  • If the SSL part is taking too long, we may want to consider enabling HTTP/2 to benefit from ALPN, adjusting our cache-control headers, and finally switching to a CDN service. “Web Performance in a Nutshell: HTTP/2, CDNs and Browser Caching” is a thorough article on this topic, as is “Analyzing HTTPS Performance Overhead” by KeyCDN.
  • ConnectSend, and Receive parts usually depend on network latency, so these can be improved by hosting close to your intended audience, making sure your host has a fast uplink, and using a CDN. For these items, you may want to consider a ping tool too (not to be confused with the Pingdom tools mentioned above), to make sure your server is responsive.
  • The Wait part — the yellow part of the waterfall — is the time your server infrastructure takes to produce or return the requested website. If this part takes too much time, you may want to return to our previous topics of optimizing the server, WordPress installation, and database stack. Or you may consider various layers of caching.

To get a more extensive testing and hand-holding tips on improving the website, there’s a little command line utility called webcoach. In an environment with NodeJS and npm installed (like Homestead Improved), installing it is simple:

npm install webcoach -g

After it’s been installed, we can get detailed insights and advice on how to improve our website’s various aspects, including performance:

webcoach command

Caching

Caching can make all the difference when managing a WordPress website. There are a few layers and possible ways of caching.

Page Caching

Page caching is caching of the entire HTML output of a web application.

If we can, we should try to test the server-level solutions first, like NGINX caching, or Varnish, or caching systems offered by managed host vendors like Kinsta, Siteground, and others.

Siteground Optimizer

If this doesn’t turn out to be as helpful as we’d like, we may want to consider plugins like WP Super CacheWP Fastest Cache, or the overhauled W3 Total Cache from GitHub. All of these can improve performance, but usually require some experimenting. Badly configured caching solutions can actually harm the site’s performance. W3TC, for example — at least before the overhaul — is known to be maybe the best free caching solution, doing real wonders … when it works. When it doesn’t, it can take your website offline.

WP Rocket is known to be maybe the most praised of the premium caching solutions.

Page caching can improve performance drastically, serving entire websites from RAM, but be aware that it can introduce complications if you have a dynamic website with a cart, or parts that depend on cookies or a personalized front end. It can serve one user’s UI parts to another user, so it usually needs to be tested before being put into production. This especially applies to solutions on non-managed servers, like Varnish or Cloudflare page cache.

Fragment caching

Fragment caching is a solution to think about when dynamic, cookie-dependent websites become hard to cache with a full-page approach, or when we are caching Ajax requests. A good introduction is available here.

 

Object cache

Object cache means compiling and storing in-memory all the database queries and PHP objects. Some caching plugins try to manage object-cache back ends for us. The back ends used are usually APCu, Memcached and Redis.
They need to be installed on the server.

To go deeper into benchmarking our PHP code and the performance of our object caching, a valuable tool which requires shell access and wp-cli installed is the profile command. We can install it with:

wp package install git@github.com:wp-cli/profile-command.git

or

wp package install wp-cli/profile-command

(You may need to add the --allow-root flag, depending on the installation.)

Then we can profile the whole load cycle, or drill down to specific hooks, files and classes, their load time and caching ratio.

wp profile command

Browser caching

Browser caching means forcing visitors’ browsers to keep static files in their cache, so they don’t need to get them from our server on repeat visits. cache-control and expires headers are used here. Caching plugins often manage browser caching and setting the headers. Technumero made a guide that goes into more depth.

Static Files

Static files are images, stylesheets, JS code, fonts, media files, etc. We should make sure we compress them, and that we’re leveraging HTTP/2 to serve these files if possible. If our managed hosting doesn’t support HTTP/2, or moving our unmanaged VPS to HTTP/2 is out of reach, the easiest way is to implement a CDN into our stack. CDNs serve our static files from data centers closest to our audience. This decreases latency and usually means taking advantage of their highly tuned infrastructure.

Autooptimize is one plugin that can help manipulate our static assets, and reduce the number of requests, concatenating JS and stylesheet files, minifying them and thus shrinking the page output.

Regarding media files, we should consider compressing/encoding our videos to reduce their size, and serving them through providers like YouTube, to reduce the strain on our servers. Cloud storage providers like Amazon S3 are another good option. Video hosting is out of scope of this article, but WPMUDEV made a handy guide about the topic.

Regarding images, these are often too big for the web. Sometimes the only solution that will allow our server to breathe — and might take a lengthy amount of time — is batch compression through the shell. Imagemagick on Linux has a useful convert tool that allows us to batch compress our images. This example does it recursively with all JPGs in a folder, reducing JPEG quality to 80%, along with other small enhancements, and resizing the images (it should be self-explanatory):

for file in *.jpg; do convert "${file}" -resize 20% -sharpen 3 -sharpen 2 -brightness-contrast "0x26" -quality 80 thumb."${file}"; done

WP Bullet has two excellent guides to batch compress JPG and PNG files.

Apart from that, there’s the Imagify service and the accompanying WordPress plugin to reduce image sizes, EWWW image optimizer, and others…

 

Other random tips

  • Memorymake sure your installation has enough.

  • XML-RPC and login page can often suffer from automated, scripted brute-force attacks — even if one isn’t a big fish. Even without breaking in, they can waste the CPU cycles. We should try to stop them on the server-level, before our WordPress installation is loaded. If we don’t need the access to xml-rpc.php, we can put this snippet inside our virtual host block on nginx:

    location = /xmlrpc.php {    
        deny all;    
    }
    

    In Apache:

    <Files xmlrpc.php>
        deny from all
    </Files>
    

    Plugins like iThemes SecurityWPS Hide login and others can help with this and with changing our login page URL.

    If you’re under brute force attacks and you aren’t protected by a CDN like Cloudflare — or a managed host’s protection — consider a firewall like fail2ban (you should probably have a firewall in place whether under attack or not).

  • WordPress Heartbeat: polling the server while WordPress dashboard is open can slow your server, and make your dashboard unresponsive. Especially if it’s open in multiple browser tabs or by several users. The HeartBeat plugin can help solve that.

  • MAX_INPUT_VARS: when saving posts with lots of meta fields, or variable products with WooCommerce, we may reach a limit of maximum allowed request variables (variables sent by complex WooCommerce products can go into thousands). This can bring down your server. Here’s how to fix it.

  • If your WordPress installation with a big database — especially a WooCommerce installation — starts having issues with speed that you can’t solve otherwise, consider ElasticPress. Some have had luck with it.

  • If you use WordFence, make sure to turn off the Live View feature. It can bring to a halt even a VPS with couple of gigabytes of memory.

  • If you’re logging access to your website — particularly in debug.log in your wp-content directory — mind its size. It can grow to the level of gigabytes and crash your server.

  • If you have system crashes on your server/hosting, core dumps will fill up your storage. Have someone analyze the reasons of those crashes, and then delete those files. You’ll recognize them by patterns that look like core.XXXXXX.

All this said, a repeat warning is in order: before you do any changes to your website, back it up!

Conclusion

I hope this compilation of WordPress optimization tips will come in handy. As sites grow in size, the tricks are harder and harder to retroactively apply. That’s why it’s best to start early, and strive for a maximum effect: apply as many of these techniques before you launch, and you’ll not only have a smooth launch, but also a performant app from day 1 — surely a fantastic experience for all new users.

Make sure you also check out SitePoint’s PWA guide. Making your WP site as PWA as possible from day 0 will help users install it on the home screens of their devices, priming them for repeat visits.

Originally found here .

How to Draw Class Diagrams

When it comes to system construction, a class diagram is the most widely used diagram. This diagram generally consists of interfacesclassesassociations and collaborations. Such a diagram would illustrate the object-oriented view of a system, which is static in nature. The object orientation of a system is indicated by a class diagram.

Since class diagrams are used for many different purposes, such as making stakeholders aware of requirements to highlighting your detailed design, you need to apply a different style in each circumstance.

The points that are going to be covered are indicated as follows:

  1. General issues
  2. Classes
  3. Interfaces
  4. Relationships
  5. Inheritance
  6. Aggregation and Composition

UML is popular for its diagrammatic notations. We all know that UML is for visualizing, specifying, constructing and documenting the components of software and non-software systems. Hence, visualization is the most important part which needs to be understood and remembered.

UML notations are the most important elements in modeling. Efficient and appropriate use of notations is very important for making a complete and meaningful model. The model is useless, unless its purpose is depicted properly.

Hence, learning notations should be emphasized from the very beginning. Different notations are available for things and relationships. UML diagrams are made using the notations of things and relationships. Extensibility is another important feature which makes UML more powerful and flexible.

The chapter describes basic UML notations in detail. This is just an extension to the UML building block section discussed in Chapter Two.

Structural Things

Graphical notations used in structural things are most widely used in UML. These are considered as the nouns of UML models. Following are the list of structural things.

  • Classes
  • Object
  • Interface
  • Collaboration
  • Use case
  • Active classes
  • Components
  • Nodes

Class Notation

UML class is represented by the following figure. The diagram is divided into four parts.

  • The top section is used to name the class.
  • The second one is used to show the attributes of the class.
  • The third section is used to describe the operations performed by the class.
  • The fourth section is optional to show any additional components.

Class Notation

Classes are used to represent objects. Objects can be anything having properties and responsibility.

Object Notation

The object is represented in the same way as the class. The only difference is the name which is underlined as shown in the following figure.

Object Notation

As the object is an actual implementation of a class, which is known as the instance of a class. Hence, it has the same usage as the class.

Interface Notation

Interface is represented by a circle as shown in the following figure. It has a name which is generally written below the circle.

Interface Notation

Interface is used to describe the functionality without implementation. Interface is just like a template where you define different functions, not the implementation. When a class implements the interface, it also implements the functionality as per requirement.

Collaboration Notation

Collaboration is represented by a dotted eclipse as shown in the following figure. It has a name written inside the eclipse.

Collaboration Notation

Collaboration represents responsibilities. Generally, responsibilities are in a group.

Use Case Notation

Use case is represented as an eclipse with a name inside it. It may contain additional responsibilities.

Use case Notation

Use case is used to capture high level functionalities of a system.

Actor Notation

An actor can be defined as some internal or external entity that interacts with the system.

Actor Notation

An actor is used in a use case diagram to describe the internal or external entities.

Initial State Notation

Initial state is defined to show the start of a process. This notation is used in almost all diagrams.

Initial state Notation

The usage of Initial State Notation is to show the starting point of a process.

Final State Notation

Final state is used to show the end of a process. This notation is also used in almost all diagrams to describe the end.

Final state Notation

The usage of Final State Notation is to show the termination point of a process.

Active Class Notation

Active class looks similar to a class with a solid border. Active class is generally used to describe the concurrent behavior of a system.

Active class Notation

Active class is used to represent the concurrency in a system.

Component Notation

A component in UML is shown in the following figure with a name inside. Additional elements can be added wherever required.

Component Notation

Component is used to represent any part of a system for which UML diagrams are made.

Node Notation

A node in UML is represented by a square box as shown in the following figure with a name. A node represents the physical component of the system.

Node Notation

Node is used to represent the physical part of a system such as the server, network, etc.

Behavioral Things

Dynamic parts are one of the most important elements in UML. UML has a set of powerful features to represent the dynamic part of software and non-software systems. These features include interactions and state machines.

Interactions can be of two types −

  • Sequential (Represented by sequence diagram)
  • Collaborative (Represented by collaboration diagram)

Interaction Notation

Interaction is basically a message exchange between two UML components. The following diagram represents different notations used in an interaction.

Interaction Notation

Interaction is used to represent the communication among the components of a system.

State Machine Notation

State machine describes the different states of a component in its life cycle. The notations are described in the following diagram.

State machine Notation

State machine is used to describe different states of a system component. The state can be active, idle, or any other depending upon the situation.

Grouping Things

Organizing the UML models is one of the most important aspects of the design. In UML, there is only one element available for grouping and that is package.

Package Notation

Package notation is shown in the following figure and is used to wrap the components of a system.

package Notation

Annotational Things

In any diagram, explanation of different elements and their functionalities are very important. Hence, UML has notes notation to support this requirement.

Note Notation

This notation is shown in the following figure. These notations are used to provide necessary information of a system.

Note Notation

Relationships

A model is not complete unless the relationships between elements are described properly. The Relationship gives a proper meaning to a UML model. Following are the different types of relationships available in UML.

  • Dependency
  • Association
  • Generalization
  • Extensibility

Dependency Notation

Dependency is an important aspect in UML elements. It describes the dependent elements and the direction of dependency.

Dependency is represented by a dotted arrow as shown in the following figure. The arrow head represents the independent element and the other end represents the dependent element.

Dependency Notation

Dependency is used to represent the dependency between two elements of a system

Association Notation

Association describes how the elements in a UML diagram are associated. In simple words, it describes how many elements are taking part in an interaction.

Association is represented by a dotted line with (without) arrows on both sides. The two ends represent two associated elements as shown in the following figure. The multiplicity is also mentioned at the ends (1, *, etc.) to show how many objects are associated.

Association Notation

Association is used to represent the relationship between two elements of a system.

Generalization Notation

Generalization describes the inheritance relationship of the object-oriented world. It is a parent and child relationship.

Generalization is represented by an arrow with a hollow arrow head as shown in the following figure. One end represents the parent element and the other end represents the child element.

Generalization Notation

Generalization is used to describe parent-child relationship of two elements of a system.

Extensibility Notation

All the languages (programming or modeling) have some mechanism to extend its capabilities such as syntax, semantics, etc. UML also has the following mechanisms to provide extensibility features.

  • Stereotypes (Represents new elements)
  • Tagged values (Represents new attributes)
  • Constraints (Represents the boundaries)

Extensibility Notation

Extensibility notations are used to enhance the power of the language. It is basically additional elements used to represent some extra behavior of the system. These extra behaviors are not covered by the standard available notations.

 

General Issues

This section describes style guidelines that are relevant to various types of class diagrams.

  1. Show visibility only on design models
  2. Assess responsibilities on domain class diagrams
  3. Highlight language-dependent visibility with property strings
  4. Highlight types only on design models
  5. Highlight types on analysis models only when the type is an actual requirement

  • – Design class diagrams should reflect language naming conventions. In the “Analysis and design version of a class” image you see that the design version of the Order class uses names that conform to common Java programming conventions such as placementDateand calculateTaxes().

  • – Model association classes on analysis diagrams. The image that shows the “Modelling association classes” indicates the association classes that are depicted as class attached via a dashed line to an association – the association line, the class, and the dashed line are considered one symbol in the UML.
  • – Do not name associations that have association classes.
  • – Center the dashed line of an association class.

Class Style

A class is basically a template from which objects are created.  Classes define attributes, information that are relevant to their instances, operations, and functionality that the objects support.  Some of the more important guidelines pertinent to classes are listed down below.

  1. Put common terminology for names
  2. Choose complete singular nouns over class names
  3. Name operations with a strong verb
  4. Name attributes with a domain-based noun
  5. Do not model scaffolding code.  Scaffolding code refers to the attributes and operations required to use basic functionality within your classes, such as the code required to implement relationships with other classes.  The image above depicts the difference between the OrderItem class without scaffolding code
  6. Never show classes with just two compartments
  7. Label uncommon class compartments
  8. Include an ellipsis ( … ) at the end of incomplete lists
  9. List static operations/attributes before instance operations/attributes
  10. List operations/attributes in decreasing visibility
  11. For parameters that are objects, only list their type
  12. Develop consistent method signatures
  13. Avoid stereotypes implied by language naming conventions
  14. Indicate exceptions in an operation’s property string.  Exceptions can be indicated with a UML property string, an example of which is shown in the above image.

Interfaces

An interface can be defined as collection of operation signature and/or attribute definitions that ideally defines a cohesive set of behaviors.  Interfaces are implemented, “realized” in UML parlance, by classes and components. In order to realize an interface, a class or component should use the operations and attributes that are defined by the interface.  Any given class or component may use zero or more interfaces and one or more classes or components can use the same interface.

  1. Interface definitions must reflect implementation language constraints.  In the above image, you see that a standard class box has been used to define the interface PersistentObject (note the use of the <<interface>> stereotype).
  2. Name interfaces according to language naming conventions
  3. Apply “Lollipop” notation to indicate that a class realizes an interface
  4. Define interfaces separately from your classes
  5. Do not model the operations and attributes of an interface in your classes. In the above image, you’ll notice that the shipment class does not include the attributes or operations defined by the two interfaces that it realizes
  6. Consider an interface to be a contract

Aggregation and Composition

As it is known an object is made up of other objects. If you were to consider as examples where an airplane consists of wings, a fuselage, engines, flaps, landing gear and so on. A delivery shipment would contain one or more packages and a team consists of two or more employees. These are all examples of the concept of aggregation that illustrates “is part of” relationships. An engine is part of a plane, a package is part of a shipment, and an employee is part of a team. Aggregation is a specialization of association, highlighting an entire-part relationship that exists between two objects. Composition is a much potent form of aggregation where the whole and parts have coincident lifetimes, and it is very common for the whole to manage the lifecycle of its parts. If you were to consider a stylistic point of view, aggregation and composition are both specializations of association where the guidelines for associations do apply.

  1. You should be interested in both the whole and the part
  2. Depict the whole to the left of the part
  3. Apply composition to aggregates of physical items

Inheritance

Inheritance models “is a” and “is like” relationships, enabling you to rather conveniently reuse data and code that already exist. When “A” inherits from “B” we say that “A” is the subclass of “B” and that “B” is the superclass of “A.” In addition to this, we have “pure inheritance” when “A” inherits all of the attributes and methods of “B”. The UML modeling notation for inheritance is usually depicted as a line that has a closed arrowhead, which points from the subclass right down to the superclass.

  1. Plus in the sentence rule for inheritance
  2. Put subclasses below superclasses
  3. Ensure that you are aware of data-based inheritance
  4. A subclass must inherit everything

Relationship

At this particular juncture, the term “relationships” will encompass all UML concepts such as aggregation, associations, dependencies, composition, realizations, and inheritance. In other words, if it’s a line on a UML class diagram, it can be considered as a relationship. The following guidelines could be considered as “best practices” and and effort should be made to adhere to them at all times.

Figure A

Figure B

Figure C

  1. Ensure that you model relationships horizontally
  2. Collaboration means a need for a relationship
  3. Model a dependency when a relationship is in transition
  4. Depict similar relationships involving a common class as a tree.  In Figure A you see that both Delivery and Order have a dependency on OIDGenerator. Note how the two dependencies are drawn in combination in “tree configuration”, instead of as two separate lines, to reduce clutter in the diagram.
  5. As a rule it is best to always indicate the multiplicity
  6. Avoid a multiplicity of “*” to avoid confusion
  7. Replace relationships by indicating attribute types.  In Figure C you see that the customer has a shippingAddress attribute of type Address – part of the scaffolding code to maintain the association between customer objects and address objects.
  8. Never model implied relationships
  9. Never model every single dependency
  10. Center names on associations
  11. Write concise association names in active voice
  12. Indicate directionality to clarify an association name
  13. Name unidirectional associations in the same direction
  14. Word association names left-to-right
  15. Indicate role names when multiple associations between two classes exist
  16. Indicate role names on recursive associations
  17. Make associations bi-directional only when collaboration occurs in both directions. The lives at association of Figure B is uni-directional.
  18. Redraw inherited associations only when something changes
  19. Question multiplicities involving minimums and maximums

Image from – http://www.digestivehealth.com.au/referral-guidelines.htm
Original post:
https://creately.com/diagram-type/article/simple-guidelines-drawing-uml-class-diagrams

UML Class Diagram Tutorial

The UML Class diagram is a graphical notation used to construct and visualize object oriented systems. A class diagram in the Unified Modeling Language (UML) is a type of static structure diagram that describes the structure of a system by showing the system’s:

  • classes,
  • their attributes,
  • operations (or methods),
  • and the relationships among objects.

What is a Class?

A Class is a blueprint for an object. Objects and classes go hand in hand. We can’t talk about one without talking about the other. And the entire point of Object-Oriented Design is not about objects, it’s about classes, because we use classes to create objects. So a class describes what an object will be, but it isn’t the object itself.

In fact, classes describe the type of objects, while objects are usable instances of classes. Each Object was built from the same set of blueprints and therefore contains the same components (properties and methods). The standard meaning is that an object is an instance of a class and object – Objects have states and behaviors.

Example

A dog has states – color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.

What is a class?

 

UML Class Notation

A class represent a concept which encapsulates state (attributes) and behavior (operations). Each attribute has a type. Each operation has a signatureThe class name is the only mandatory information.

UML Class Notation

 

Class Name:

  • The name of the class appears in the first partition.

Class Attributes:

  • Attributes are shown in the second partition.
  • The attribute type is shown after the colon.
  • Attributes map onto member variables (data members) in code.

Class Operations (Methods):

  • Operations are shown in the third partition. They are services the class provides.
  • The return type of a method is shown after the colon at the end of the method signature.
  • The return type of method parameters are shown after the colon following the parameter name. Operations map onto class methods in code

Class Operations

 

Class Visibility

The +, – and # symbols before an attribute and operation name in a class denote the visibility of the attribute and operation.

Class Visibility

 
  • + denotes public attributes or operations
  • – denotes private attributes or operations
  • # denotes protected attributes or operations
 

Parameter Directionality

Each parameter in an operation (method) may be denoted as in, out or inout which specifies its direction with respect to the caller. This directionality is shown before the parameter name.

Parameter Directionality

 

Perspectives of Class Diagram

The choice of perspective depends on how far along you are in the development process. During the formulation of a domain model, for example, you would seldom move past the conceptual perspectiveAnalysis models will typically feature a mix of conceptual and specification perspectivesDesign model development will typically start with heavy emphasis on the specification perspective, and evolve into the implementation perspective.

A diagram can be interpreted from various perspectives:

  • Conceptual: represents the concepts in the domain
  • Specification: focus is on the interfaces of Abstract Data Type (ADTs) in the software
  • Implementation: describes how classes will implement their interfaces

The perspective affects the amount of detail to be supplied and the kinds of relationships worth presenting. As we mentioned above, the class name is the only mandatory information.

Perspectives of Class Diagram

 

Relationships between classes

UML is not just about pretty pictures. If used correctly, UML precisely conveys how code should be implemented from diagrams. If precisely interpreted, the implemented code will correctly reflect the intent of the designer. Can you describe what each of the relationships mean relative to your target programming language shown in the Figure below?

If you can’t yet recognize them, no problem this section is meant to help you to understand UML class relationships. A class may be involved in one or more relationships with other classes. A relationship can be one of the following types:

Relationships between classes

 

Inheritance (or Generalization):

A generalization is a taxonomic relationship between a more general classifier and a more specific classifier. Each instance of the specific classifier is also an indirect instance of the general classifier. Thus, the specific classifier inherits the features of the more general classifier.

  • Represents an “is-a” relationship.
  • An abstract class name is shown in italics.
  • SubClass1 and SubClass2 are specializations of SuperClass.

The figure below shows an example of inheritance hierarchy. SubClass1 and SubClass2 are derived from SuperClass. The relationship is displayed as a solid line with a hollow arrowhead that points from the child element to the parent element.

Inheritance (or Generalization)

 

Inheritance Example – Shapes

The figure below shows an inheritance example with two styles. Although the connectors are drawn differently, they are semantically equivalent.

Inheritance Example - Shapes

 

Association

Associations are relationships between classes in a UML Class Diagram. They are represented by a solid line between classes. Associations are typically named using a verb or verb phrase which reflects the real world problem domain.

 

Simple Association

  • A structural link between two peer classes.
  • There is an association between Class1 and Class2

The figure below shows an example of simple association. There is an association that connects the <> class Class1 and <> class Class2. The relationship is displayed as a solid line connecting the two classes.

Simple Association

 

Cardinality

Cardinality is expressed in terms of:

  • one to one
  • one to many
  • many to many

Cardinality

Aggregation

A special type of association.

  • It represents a “part of” relationship.
  • Class2 is part of Class1.
  • Many instances (denoted by the *) of Class2 can be associated with Class1.
  • Objects of Class1 and Class2 have separate lifetimes.

The figure below shows an example of aggregation. The relationship is displayed as a solid line with a unfilled diamond at the association end, which is connected to the class that represents the aggregate.

Aggregation

 

Composition

  • A special type of aggregation where parts are destroyed when the whole is destroyed.
  • Objects of Class2 live and die with Class1.
  • Class2 cannot stand by itself.

The figure below shows an example of composition. The relationship is displayed as a solid line with a filled diamond at the association end, which is connected to the class that represents the whole or composite.

Composition

 

Dependency

An object of one class might use an object of another class in the code of a method. If the object is not stored in any field, then this is modeled as a dependency relationship.

  • A special type of association.
  • Exists between two classes if changes to the definition of one may cause changes to the other (but not the other way around).
  • Class1 depends on Class2

The figure below shows an example of dependency. The relationship is displayed as a dashed line with an open arrow.

Dependency

The figure below shows another example of dependency. The Person class might have a hasRead method with a Book parameter that returns true if the person has read the book (perhaps by checking some database).

Dependency

 

Realization

Realization is a relationship between the blueprint class and the object containing its respective implementation level details. This object is said to realize the blueprint class. In other words, you can understand this as the relationship between the interface and the implementing class.

For example, the Owner interface might specify methods for acquiring property and disposing of property. The Person and Corporation classes need to implement these methods, possibly in very different ways.

Realization

 

Class Diagram Example: Order System

 

Class Diagram Example: Order System

 

Class Diagram Example: GUI

A class diagram may also have notes attached to classes or relationships.

Class Diagram Example: GUI

Original link here

Unified Modeling Language

We have concentrated on the kind of information that should be included in architecture documentation. Architecture in some sense expresses what is essential about a software system, and that essence is independent of languages and notations to capture it. Nevertheless, today the Unified Modeling Language (UML) has emerged as the de facto standard notation for documenting a software architecture. However, it must be said that UML makes its main contribution in a view’s primary presentation, and its secondary contribution in the behavior of an element or group of elements. It is up to the architect to augment the UML pictures with the necessary supporting documentation (the element catalog, the rationale, and so forth) that a responsible job requires. UML provides no direct support for components, connectors, layers, interface semantics, or many other aspects of a system that are supremely architectural.

Still, in most cases we can use the constructs that UML does offer to achieve satisfactory effects, at least in crafting the primary presentations of architectural views. We begin by discussing module views.

MODULE VIEWS

Recall that a module is a code or implementation unit and a module view is an enumeration of modules together with their interfaces and their relations.

Interfaces

Figure 9.4 shows how module interfaces can be represented in UML. UML uses a “lollipop” to denote an interface, which can be appended to classes and subsystems, among other things.

UML also allows a class symbol (box) to be stereotyped as an interface; the open-headed dashed arrow shows that an element realizes an interface. The bottom of the class symbol can be annotated with the interface’s signature information: method names, arguments, argument types, and so forth. The lollipop notation is normally used to show dependencies from elements to the interface, while the box notation allows a more detailed description of the interface’s syntax, such as the operations it provides.

Modules

UML provides a variety of constructs to represent different kinds of modules. Figure 9.5 shows some examples. UML has a class construct, which is the object-oriented specialization of a module. Packages can be used in cases where grouping of functionality is important, such as to represent layers and classes. The subsystem construct can be used if a specification of interface and behavior is required.

Figure 9.5. Examples of module notations in UML

graphics/09fig05.gif

Figure 9.6 shows how the relations native to module views are denoted using UML. Module decomposition relies on the “is-part-of” relation. The module uses view relies on the dependency relation, and the module class view relies on the generalization, or “is-a” relation (also called “inheritance”).

Figure 9.6. Examples of relation notations in UML. Module B is part of module A, module D depends on module C, and module F is a type of module E.

graphics/09fig06.gif

Aggregation

In UML, the subsystem construct can be used to represent modules that contain other modules; the class box is normally used for the leaves of the decomposition. Subsystems are used both as packages and as classifiers. As packages, they can be decomposed and hence are suitable for module aggregation. As classifiers, they encapsulate their contents and can provide an explicit interface. Aggregation is depicted in one of three ways in UML:

  • Modules may be nested (see Figure 9.7 left).

    Figure 9.7. Decomposition in UML with nesting. The aggregate module is shown as a package (left); decomposition in UML with arcs (right).

    graphics/09fig07.gif

  • A succession of two diagrams (possibly linked) can be shown, where the second is a depiction of the contents of a module shown in the first.

  • An arc denoting composition is drawn between the parent and the children (see Figure 9.7 right).

In UML, composition is a form of aggregation with implied strong ownership-that is, parts live and die with the whole. If module A is composed of modules B and C, then B or C cannot exist without A, and if A is destroyed at runtime, so are B and C. Thus, UML’s composition relation has implications beyond the structuring of the implementation units; the relation also endows the elements with a runtime property. As an architect, you should make sure you are comfortable with this property before using UML’s composition relation.

Generalization

Expressing generalization is at the heart of UML in which modules are shown as classes (although they may also be shown as subsystems). Figure 9.8 shows the basic notation available in UML.

Figure 9.8. Documenting generalization in UML with two line styles

graphics/09fig08.gif

The two diagrams in Figure 9.8 are semantically identical. UML allows an ellipsis (…) in place of a submodule, indicating that a module can have more children than shown and that additional ones are likely. Module Shape is the parent of modules Polygon, Circle, and Spline, each of which is a subclass, child, or descendant of Shape. Shape is more general, while its children are specialized versions.

Dependency

The basic notation for dependency was shown in Figure 9.6. The most architecturally significant manifestation of dependency is found in layers. Sadly, UML has no built-in primitive corresponding to a layer. However, it can represent simple layers using packages, as shown in Figure 9.9. These are general-purpose mechanisms for organizing elements into groups. UML has predefined packages for systems and subsystems. We can introduce an additional package for layers by defining it as a package stereotype. A layer can be shown as a UML package with the constraints that it groups modules together and that the dependency between packages is “allowed to use.” We can designate a layer using the package notation with the stereotype name <<layer>> preceding the layer name, or introduce a new visual form, such as a shaded rectangle.

Figure 9.9. A simple representation of layers in UML

graphics/09fig09.gif

COMPONENT-AND-CONNECTOR VIEWS

There is no single preferred strategy to document component-and-connector (C&C) views in UML, but a number of alternatives. Each alternative has its advantages and disadvantages. One natural candidate for representing component-and-connector types begins with the UML class concept.

Figure 9.10 illustrates the general idea using a simple pipe-and-filter system. Here, the filter architectural type is represented as the UML class Filter. Instances of filters, such as Splitter, are represented as corresponding objects in an object instance diagram. To provide a namespace boundary, we enclose the descriptions in packages. The representation of MergeAndSort, denoted Details, would be shown as another package elsewhere.

Figure 9.10. Types as classes, and instances as objects, exemplified with a simple pipe and filter

graphics/09fig10.gif

We now take a closer look at this strategy.

Components

The type/instance relationship in architectural descriptions is a close match to the class/object relationship in a UML model. UML classes, like component types in architectural descriptions, are first-class entities and are rich structures for capturing software abstractions. The full set of UML descriptive mechanisms is available to describe the structure, properties, and behavior of a class, making this a good choice for depicting detail and using UML-based analysis tools. Properties of architectural components can be represented as class attributes or with associations; behavior can be described using UML behavioral models; and generalization can be used to relate a set of component types. The semantics of an instance or type can also be elaborated by attaching one of the standard stereotypes; for example, the «process» stereotype can be attached to a component to indicate that it runs as a separate process. Note that the relationship between MergeAndSort and its substructure is indicated using a dependency relation.

Interfaces

Interfaces to components, sometimes called ports, can be shown in five ways, as shown in Figure 9.11, described in increasing order of expressiveness. However, as expressiveness rises so does complexity, so you should pick the first strategy that will serve your purposes.

  • Option 1: No explicit representation. Leaving out interfaces leads to the simplest diagrams but suffers from the obvious problem that there is no way to characterize the names or the properties of the interfaces in the primary presentation. Still, this choice might be reasonable if the components have only one interface, if the interfaces can be inferred from the system topology, or if the diagram is refined elsewhere.

  • Option 2: Interfaces as annotations. Representing interfaces as annotations provides a home for information about them, although annotations have no semantic value in UML so cannot be used as a basis for analysis. Again, if the detailed properties of an interface are not of concern, this approach might be reasonable.

  • Option 3: Interfaces as class/object attributes. Treating interfaces as attributes of a class/object makes them part of the formal structural model, but they can have only a simple representation in a class diagram-essentially, a name and a type. This restriction limits the expressiveness of this option.

  • Option 4: Interfaces as UML interfaces. The UML lollipop notation provides a compact description of an interface in a class diagram depicting a component type. In an instance diagram, a UML association role, corresponding to an interface instance and qualified by the interface type name, provides a compact way to show that a component instance is interacting through a particular interface instance. This approach provides visually distinct depictions of components and interfaces, in which interfaces can clearly be seen as subservient.

    However, this strategy provides no means to depict the services required from a component’s environment, often a key part of an interface. Furthermore, it is meaningful for a component type to have several instances of the same interface type, but it is not meaningful to say that a class realizes several versions of one UML interface. For example, there is no easy way to define a Splitter filter type that has two output ports of the same “type” using this technique. Finally, unlike classes, UML interfaces do not have attributes or substructure.

  • Option 5: Interfaces as classes. Describing interfaces as classes contained by a component type overcomes the lack of expressiveness of the previous alternatives: We can now represent interface substructure and indicate that a component type has several interfaces of the same type. A component instance is modeled as an object containing a set of interface objects. However, by representing interfaces as classes, we not only clutter the diagram but also lose clear visual discrimination between interfaces and components. We could use a notational variation in which the interfaces are contained classes, as shown in the lower part of option 5 in Figure 9.11. Indicating points of interaction is counterintuitive, however, as containment usually indicates that a class owns other classes whose instances may or may not be accessible through instances of the parent class.

Figure 9.11. Five ways to represent interfaces to components (ports)

graphics/09fig11.gif

Connectors

There are three reasonable options for representing connectors. Again, the choice is between expressiveness and semantic match on the one hand and complexity on the other.

  • Option 1: Connector types as associations and connector instances as links. In an architectural box-and-line diagram of a system, the lines between components are connectors. One tempting way to represent connectors in UML is as associations between classes or links between objects. This approach is visually simple, provides a clear distinction between components and connectors, and uses the most familiar relationship in UML class diagrams: association. Moreover, associations can be labeled, and a direction associated with the connector can be indicated with an arrow. Unfortunately, connectors and associations have different meanings. A system in an architectural description is built up by choosing components with behavior exposed through their interfaces and connecting them with connectors that coordinate their behaviors. A system’s behavior is defined as the collective behavior of a set of components whose interaction is defined and limited by the connections between them.

    In contrast, although an association, or link, in UML represents a potential for interaction between the elements it relates, the association mechanism is primarily a way of describing a conceptual relationship between two elements. In addition, an association is a relationship between UML elements, so it cannot stand on its own in a UML model. Consequently, a connector type cannot be represented in isolation. Instead, you must resort to naming conventions or to stereotypes whose meanings are captured by description in UML’s object constraint language. Further, the approach does not allow you to specify a connector’s interfaces.

  • Option 2: Connector types as association classes. One solution to the lack of expressiveness is to qualify the association with a class that represents the connector type. In this way, the connector type or connector attributes can be captured as attributes of a class or object. Unfortunately, this technique still does not provide any way of explicitly representing connector interfaces.

  • Option 3: Connector types as classes and connector instances as objects. One way to give connectors first-class status in UML is to represent connector types as classes and connector instances as objects. Using classes and objects, we have the same four options for representing roles as we had for interfaces: not at all, as annotations, as interfaces realized by a class, or as child classes contained by a connector class. Given a scheme for representing interfaces, an attachment between a component’s interface and a connector’s interface may be represented as an association or a dependency.

Systems

In addition to representing individual components and connectors and their types, we also need to encapsulate graphs of components and connectors: systems. Three options are available.

  • Option 1: Systems as UML subsystems. The primary UML mechanism for grouping related elements is the package. In fact, UML defines a standard package stereotype, called «subsystem», to group UML models that represent a logical part of a system. The choice of subsystems is appropriate for any mapping of components and connectors, and it works particularly well for grouping classes. One of the problems with using subsystems, as defined in UML 1.4, is that, although they are both a classifier and a package, the meaning is not entirely clear. Some have argued that we should be able to treat a subsystem as an atomic class-like entity at certain stages in the development process and later be able to refine it in terms of a more detailed substructure. Having the ability to do this would make the subsystem construct more appropriate for modeling architectural components.

  • Option 2: Systems as contained objects. Object containment can be used to represent systems. Components are represented as instances of contained classes, and connectors are modeled using one of the options outlined earlier. Objects provide a strong encapsulation boundary and carry with them the notion that each instance of the class has the associated “substructure.” However, this approach has problems, the most serious being that associations, used to model connectors, between contained classes are not scoped by the class. That is, it is not possible to say that a pair of classes interacts via a particular connector, modeled as an association, only in the context of a particular system. So, for example, indicating that two contained classes interact via an association is valid for instances of classes used anywhere else in the model.

  • Option 3: Systems as collaborations. A set of communicating objects connected by links is described in UML using a collaboration. If we represent components as objects, we can use collaborations to represent systems. A collaboration defines a set of participants and relationships that are meaningful for a given purpose, which in this case is to describe the runtime structure of the system. The participants define classifier roles that objects play, or conform to, when interacting. Similarly, the relationships define association roles that links must conform to.

    Collaboration diagrams can be used to present collaborations at either the specification or the instance level. A specification-level collaboration diagram shows the roles, defined within the collaboration, arranged in a pattern to describe the system substructure. An instance-level collaboration diagram shows the objects and links conforming to the roles at the specification level and interacting to achieve the purpose. Therefore, a collaboration presented at the instance level is best used to represent the runtime structure of the system.

    Figure 9.12 illustrates this approach. The Filter architectural type is represented as previously. Instances of filters and pipes are represented as corresponding classifier roles-for example, /Splitter indicates the Splitter role-and association roles. The objects and links conforming to those roles are shown in the collaboration diagram at the instance level, indicated by underscored names.

    Figure 9.12. Systems as collaborations

    graphics/09fig12.gif

    Although this is a natural way to describe runtime structures, it leaves no way to explicitly represent system-level properties. There is also a semantic mismatch; a collaboration describes a representative interaction between objects and provides a partial description, whereas an architectural configuration is meant to capture a complete description.

ALLOCATION VIEWS

In UML, a deployment diagram is a graph of nodes connected by communication associations. Figure 9.13 provides an example. Nodes may contain component instances, which indicates that the component lives or runs on the node. Components may contain objects, which indicates that the object is part of the component. Components are connected to other components by dashed-arrow dependencies (possibly through interfaces). This indicates that one component uses the services of another; a stereotype may be used to indicate the precise dependency if needed. The deployment type diagram may also be used to show which components may run on which nodes, by using dashed arrows with the stereotype «supports».

Figure 9.13. A deployment view in UML

graphics/09fig13.gif

A node is a runtime physical object that represents a processing resource, generally having at least a memory and often processing capability as well. Nodes include computing devices but also human or mechanical processing resources. Nodes may represent types of instances. Runtime computational instances, both objects and components, may reside on node instances.

Nodes may be connected by associations to other nodes. An association indicates a communication path between them. The association may have a stereotype to indicate the nature of the communication path (for example, the kind of channel or network).

The nesting of symbols within the node symbol signifies a composition association between a node class and constituent classes or a composition link between a node object and constituent objects.

(link)

The Ultimate list of places you can host your apps for free


Free stuff is always exciting, and this time I am listing free hosting resources for you. Enjoy!

1. Netlify

Deploy modern static websites with Netlify. Get CDN, Continuous deployment, 1-click HTTPS, and all the services you need. Get started for free.
Link: netlify.com

2. FIrebase

Firebase Helps You Build, Improve, & Grow Your Mobile Apps. Check It Out Today! Find All The Docs You Need To Get Started With Firebase In Minutes. Learn More! Trusted by +200,000 Devs. Build Fast For Any Device. Build Extraordinary Apps.
Link: firebase.google.com

3. AWS

Amazon Web Services offers reliable, scalable, and inexpensive cloud computing services. Free to join, pay only for what you use.
Link: aws.amazon.com

4. Heroku

Heroku is a platform as a service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud.
Link: heroku.com

5. Github Pages

Websites for you and your projects, hosted directly from your GitHub repository. Just edit, push, and your changes are live. Link: pages.github.com

6. Vercel

Deploy web projects with the best frontend developer experience and highest end-user performance.
Link: vercel.com

7. Surge

Shipping web projects should be fast, easy, and low risk. Surge is static web publishing for Front-End Developers, right from the CLI.
Link: surge.sh

8. Render

Render is a unified platform to build and run all your apps and websites with free SSL, a global CDN, private networks and auto deploys from Git. Get started.
Link: render.com

9. Gitlab Pages

Learn how to use GitLab Pages to deploy a static website at no additional cost.
link: docs.gitlab.com/ee/user/project/pages

10. Stormkit

Stormkit is an infrastructure provider for modern JavaScript applications which is strongly integrated with popular Git providers.
Link: stormkit.io

11. Azure

A modern web app service that offers streamlined full-stack development from source code to global high availability.
Link: azure.microsoft.com/en-us/services/app-service/static/

12. Hostman

Hostman automates DevOps saving time to developers and costs to your business.
Link: hostman.com

13. Glitch

Simple, powerful, free tools to create and use millions of apps.
Link: glitch.com

14. Fleek

From local development to global deployment, Fleek is everything you need to build fast, modern sites & apps on IPFS. All in one seamless workflow.
Link: fleek.co

15. Begin

Begin is a ridiculously quick platform for building modern web apps, sites, & APIs. Get started for free, no credit card required.
Link: begin.com

16. HelioHost

Community powered free web hosting for everyone. PHP, Java/JSP, ASP.net, RoR, cPanel, Python, Perl, Ruby, MySQL, PostgreSQL, SQLite, Django, unlimited bandwidth.
Link: heliohost.org

17. KintoHub

KintoHub is an all-in-one platform to combine and deploy your backend services, websites, cron jobs, databases and everything your app needs in one place.
Link: kintohub.com

18. Fosshost

fosshost.org is a recognized and not-for-profit provider of free to use and accessible cloud-hosting services to the free and open source software community.
Link: fosshost.org
Original link here

Design Patterns – Builder Pattern

Builder pattern builds a complex object using simple objects and using a step by step approach. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

A Builder class builds the final object step by step. This builder is independent of other objects.

Implementation

We have considered a business case of fast-food restaurant where a typical meal could be a burger and a cold drink. Burger could be either a Veg Burger or Chicken Burger and will be packed by a wrapper. Cold drink could be either a coke or pepsi and will be packed in a bottle.

We are going to create an Item interface representing food items such as burgers and cold drinks and concrete classes implementing the Item interface and a Packing interface representing packaging of food items and concrete classes implementing the Packing interface as burger would be packed in wrapper and cold drink would be packed as bottle.

We then create a Meal class having ArrayList of Item and a MealBuilder to build different types of Meal objects by combining ItemBuilderPatternDemo, our demo class will use MealBuilder to build a Meal.

Builder Pattern UML Diagram

Step 1

Create an interface Item representing food item and packing.

Item.java

public interface Item {
   public String name();
   public Packing packing();
   public float price();	
}

Packing.java

public interface Packing {
   public String pack();
}

Step 2

Create concrete classes implementing the Packing interface.

Wrapper.java

public class Wrapper implements Packing {

   @Override
   public String pack() {
      return "Wrapper";
   }
}

Bottle.java

public class Bottle implements Packing {

   @Override
   public String pack() {
      return "Bottle";
   }
}

Step 3

Create abstract classes implementing the item interface providing default functionalities.

Burger.java

public abstract class Burger implements Item {

   @Override
   public Packing packing() {
      return new Wrapper();
   }

   @Override
   public abstract float price();
}

ColdDrink.java

public abstract class ColdDrink implements Item {

	@Override
	public Packing packing() {
       return new Bottle();
	}

	@Override
	public abstract float price();
}

Step 4

Create concrete classes extending Burger and ColdDrink classes

VegBurger.java

public class VegBurger extends Burger {

   @Override
   public float price() {
      return 25.0f;
   }

   @Override
   public String name() {
      return "Veg Burger";
   }
}

ChickenBurger.java

public class ChickenBurger extends Burger {

   @Override
   public float price() {
      return 50.5f;
   }

   @Override
   public String name() {
      return "Chicken Burger";
   }
}

Coke.java

public class Coke extends ColdDrink {

   @Override
   public float price() {
      return 30.0f;
   }

   @Override
   public String name() {
      return "Coke";
   }
}

Pepsi.java

public class Pepsi extends ColdDrink {

   @Override
   public float price() {
      return 35.0f;
   }

   @Override
   public String name() {
      return "Pepsi";
   }
}

Step 5

Create a Meal class having Item objects defined above.

Meal.java

import java.util.ArrayList;
import java.util.List;

public class Meal {
   private List<Item> items = new ArrayList<Item>();	

   public void addItem(Item item){
      items.add(item);
   }

   public float getCost(){
      float cost = 0.0f;
      
      for (Item item : items) {
         cost += item.price();
      }		
      return cost;
   }

   public void showItems(){
   
      for (Item item : items) {
         System.out.print("Item : " + item.name());
         System.out.print(", Packing : " + item.packing().pack());
         System.out.println(", Price : " + item.price());
      }		
   }	
}

Step 6

Create a MealBuilder class, the actual builder class responsible to create Meal objects.

MealBuilder.java

public class MealBuilder {

   public Meal prepareVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new VegBurger());
      meal.addItem(new Coke());
      return meal;
   }   

   public Meal prepareNonVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new ChickenBurger());
      meal.addItem(new Pepsi());
      return meal;
   }
}

Step 7

BuiderPatternDemo uses MealBuider to demonstrate builder pattern.

BuilderPatternDemo.java

public class BuilderPatternDemo {
   public static void main(String[] args) {
   
      MealBuilder mealBuilder = new MealBuilder();

      Meal vegMeal = mealBuilder.prepareVegMeal();
      System.out.println("Veg Meal");
      vegMeal.showItems();
      System.out.println("Total Cost: " + vegMeal.getCost());

      Meal nonVegMeal = mealBuilder.prepareNonVegMeal();
      System.out.println("\n\nNon-Veg Meal");
      nonVegMeal.showItems();
      System.out.println("Total Cost: " + nonVegMeal.getCost());
   }
}

Step 8

Verify the output.

Veg Meal
Item : Veg Burger, Packing : Wrapper, Price : 25.0
Item : Coke, Packing : Bottle, Price : 30.0
Total Cost: 55.0


Non-Veg Meal
Item : Chicken Burger, Packing : Wrapper, Price : 50.5
Item : Pepsi, Packing : Bottle, Price : 35.0
Total Cost: 85.5

Design Pattern – Singleton Pattern

Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.

Implementation

We’re going to create a SingleObject class. SingleObject class have its constructor as private and have a static instance of itself.

SingleObject class provides a static method to get its static instance to outside world. SingletonPatternDemo, our demo class will use SingleObject class to get a SingleObject object.

Singleton Pattern UML Diagram

Step 1

Create a Singleton Class.

SingleObject.java

public class SingleObject {

   //create an object of SingleObject
   private static SingleObject instance = new SingleObject();

   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}

   //Get the only object available
   public static SingleObject getInstance(){
      return instance;
   }

   public void showMessage(){
      System.out.println("Hello World!");
   }
}

Step 2

Get the only object from the singleton class.

SingletonPatternDemo.java

public class SingletonPatternDemo {
   public static void main(String[] args) {

      //illegal construct
      //Compile Time Error: The constructor SingleObject() is not visible
      //SingleObject object = new SingleObject();

      //Get the only object available
      SingleObject object = SingleObject.getInstance();

      //show the message
      object.showMessage();
   }
}

Step 3

Verify the output.

Hello World!

Design Patterns – MVC Pattern

MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application’s concerns.

  • Model – Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes.

  • View – View represents the visualization of the data that model contains.

  • Controller – Controller acts on both model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate.

Implementation

We are going to create a Student object acting as a model.StudentView will be a view class which can print student details on console and StudentController is the controller class responsible to store data in Student object and update view StudentView accordingly.

MVCPatternDemo, our demo class, will use StudentController to demonstrate use of MVC pattern.

MVC Pattern UML Diagram

Step 1

Create Model.

Student.java

public class Student {
   private String rollNo;
   private String name;
   
   public String getRollNo() {
      return rollNo;
   }
   
   public void setRollNo(String rollNo) {
      this.rollNo = rollNo;
   }
   
   public String getName() {
      return name;
   }
   
   public void setName(String name) {
      this.name = name;
   }
}

Step 2

Create View.

StudentView.java

public class StudentView {
   public void printStudentDetails(String studentName, String studentRollNo){
      System.out.println("Student: ");
      System.out.println("Name: " + studentName);
      System.out.println("Roll No: " + studentRollNo);
   }
}

Step 3

Create Controller.

StudentController.java

public class StudentController {
   private Student model;
   private StudentView view;

   public StudentController(Student model, StudentView view){
      this.model = model;
      this.view = view;
   }

   public void setStudentName(String name){
      model.setName(name);		
   }

   public String getStudentName(){
      return model.getName();		
   }

   public void setStudentRollNo(String rollNo){
      model.setRollNo(rollNo);		
   }

   public String getStudentRollNo(){
      return model.getRollNo();		
   }

   public void updateView(){				
      view.printStudentDetails(model.getName(), model.getRollNo());
   }	
}

Step 4

Use the StudentController methods to demonstrate MVC design pattern usage.

MVCPatternDemo.java

public class MVCPatternDemo {
   public static void main(String[] args) {

      //fetch student record based on his roll no from the database
      Student model  = retriveStudentFromDatabase();

      //Create a view : to write student details on console
      StudentView view = new StudentView();

      StudentController controller = new StudentController(model, view);

      controller.updateView();

      //update model data
      controller.setStudentName("John");

      controller.updateView();
   }

   private static Student retriveStudentFromDatabase(){
      Student student = new Student();
      student.setName("Robert");
      student.setRollNo("10");
      return student;
   }
}

Step 5

Verify the output.

Student: 
Name: Robert
Roll No: 10
Student: 
Name: John
Roll No: 10

Design Patterns – Prototype Pattern

Prototype pattern refers to creating duplicate object while keeping performance in mind. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when creation of object directly is costly. For example, an object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls.

Implementation

We’re going to create an abstract class Shape and concrete classes extending the Shape class. A class ShapeCache is defined as a next step which stores shape objects in a Hashtable and returns their clone when requested.

PrototypPatternDemo, our demo class will use ShapeCache class to get a Shape object.

Prototype Pattern UML Diagram

Step 1

Create an abstract class implementing Clonable interface.

Shape.java

public abstract class Shape implements Cloneable {
   
   private String id;
   protected String type;
   
   abstract void draw();
   
   public String getType(){
      return type;
   }
   
   public String getId() {
      return id;
   }
   
   public void setId(String id) {
      this.id = id;
   }
   
   public Object clone() {
      Object clone = null;
      
      try {
         clone = super.clone();
         
      } catch (CloneNotSupportedException e) {
         e.printStackTrace();
      }
      
      return clone;
   }
}

Step 2

Create concrete classes extending the above class.

Rectangle.java

public class Rectangle extends Shape {

   public Rectangle(){
     type = "Rectangle";
   }

   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}

Square.java

public class Square extends Shape {

   public Square(){
     type = "Square";
   }

   @Override
   public void draw() {
      System.out.println("Inside Square::draw() method.");
   }
}

Circle.java

public class Circle extends Shape {

   public Circle(){
     type = "Circle";
   }

   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}

Step 3

Create a class to get concrete classes from database and store them in a Hashtable.

ShapeCache.java

import java.util.Hashtable;

public class ShapeCache {
	
   private static Hashtable<String, Shape> shapeMap  = new Hashtable<String, Shape>();

   public static Shape getShape(String shapeId) {
      Shape cachedShape = shapeMap.get(shapeId);
      return (Shape) cachedShape.clone();
   }

   // for each shape run database query and create shape
   // shapeMap.put(shapeKey, shape);
   // for example, we are adding three shapes
   
   public static void loadCache() {
      Circle circle = new Circle();
      circle.setId("1");
      shapeMap.put(circle.getId(),circle);

      Square square = new Square();
      square.setId("2");
      shapeMap.put(square.getId(),square);

      Rectangle rectangle = new Rectangle();
      rectangle.setId("3");
      shapeMap.put(rectangle.getId(), rectangle);
   }
}

Step 4

PrototypePatternDemo uses ShapeCache class to get clones of shapes stored in a Hashtable.

PrototypePatternDemo.java

public class PrototypePatternDemo {
   public static void main(String[] args) {
      ShapeCache.loadCache();

      Shape clonedShape = (Shape) ShapeCache.getShape("1");
      System.out.println("Shape : " + clonedShape.getType());		

      Shape clonedShape2 = (Shape) ShapeCache.getShape("2");
      System.out.println("Shape : " + clonedShape2.getType());		

      Shape clonedShape3 = (Shape) ShapeCache.getShape("3");
      System.out.println("Shape : " + clonedShape3.getType());		
   }
}

Step 5

Verify the output.

Shape : Circle
Shape : Square
Shape : Rectangle