09 FEB 2020

visitor prototype extension methods

designp

Visitor pattern

The Visitor pattern defines a new operation to a collection of objects without changing the objects themselves. The new logic resides in a separate object called the Visitor.

Visitors are useful when building extensibility in a library or framework. If the objects in your project provide a ‘visit’ method that accepts a Visitor object which can make changes to the receiving object then you are providing an easy way for clients to implement future extensions.

In most programming languages the Visitor pattern requires that the original developer anticipates functional adjustments in the future. This is done by including methods that accept a Visitor and let it operate on the original collection of objects.

Visitor dofactory – link
Class code: Visitor shapes and tax example

Prototype pattern

The Prototype Pattern creates new objects, but rather than creating non-initialized objects it returns objects that are initialized with values it copied from a prototype – or sample – object. The Prototype pattern is also referred to as the Properties pattern.

An example of where the Prototype pattern is useful is the initialization of business objects with values that match the default values in the database. The prototype object holds the default values that are copied over into a newly created business object.

Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.

Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.

deep

Prototype dofactory – link
Class code: Prototype

see immutable and struct clone here in our blog – blog link

Extension Methods in C#

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C#, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

… full article

Class code: Extension methods example

Links:

 

05 FEB 2020

proxy memento decorator nullable

designp

Proxy pattern

The Proxy pattern provides a surrogate or placeholder object for another object and controls access to this other object.

In object-oriented programming, objects do the work they advertise through their interface (properties and methods). Clients of these objects expect this work to be done quickly and efficiently. However, there are situations where an object is severely constrained and cannot live up to its responsibility. Typically this occurs when there is a dependency on a remote resource (resulting in network latency) or when an object takes a long time to load.

In situations like these you apply the Proxy pattern and create a proxy object that ‘stands in’ for the original object. The Proxy forwards the request to a target object. The interface of the Proxy object is the same as the original object and clients may not even be aware they are dealing with a proxy rather than the real object

Proxy dofactory – link
Class code: Proxy ATM
Class code: Proxy for flight system

Memento pattern

The Memento pattern provides temporary storage as well as restoration of an object. The mechanism in which you store the object’s state depends on the required duration of persistence, which may vary.

You could view a database as an implementation of the Memento design pattern in which objects are persisted and restored. However, the most common reason for using this pattern is to capture a snapshot of an object’s state so that any subsequent changes can be undone easily if necessary.

Essentially, a Memento is a small repository that stores an object’s state. Scenarios in which you may want to restore an object into a state that existed previously include: saving and restoring the state of a player in a computer game or the implementation of an undo operation in a database.

Proxy dofactory – link
Class code: Memento (winform)

Nullable types

A nullable value type T? represents all values of its underlying value type T and an additional null value. For example, you can assign any of the following three values to a bool? variable: true, false, or null. An underlying value type T cannot be a nullable value type itself.
Any nullable value type is an instance of the generic System.Nullable structure. You can refer to a nullable value type with an underlying type T in any of the following interchangeable forms: Nullable or T?.
You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool, variable can only be either true or false. However, in some applications a variable value can be undefined or missing. For example, a database field may contain true or false, or it may contain no value at all, that is, NULL. You can use the bool? type in that scenario.

… full article

nice idea: implement Nullable yourself using decorator pattern

see more on value type here in our blog – blog link

Links:

 

02 FEB 2020

template-method proxy attributes

designp

Attributes

Attributes provide a powerful method of associating metadata, or declarative information, with code (assemblies, types, methods, properties, and so forth). After an attribute is associated with a program entity, the attribute can be queried at run time by using a technique called reflection

Attributes have the following properties:

  • Attributes add metadata to your program. Metadata is information about the types defined in a program. All .NET assemblies contain a specified set of metadata that describes the types and type members defined in the assembly. You can add custom attributes to specify any additional information that is required..
  • You can apply one or more attributes to entire assemblies, modules, or smaller program elements such as classes and properties.
  • Attributes can accept arguments in the same way as methods and properties.
  • Your program can examine its own metadata or the metadata in other programs by using reflection.

… full article

Template method + SQL + Reflection + Attributes – Cont.

Complete solution for query execution:

  • Select query
  • Insert query
  • Stored procedure using parameters (for select)

Class code: Full solution

Links:

29 JAN 2020

template-method reflection

designp

Template method pattern

The Template Method pattern provides an outline of a series of steps for an algorithm. Objects that implement these steps retain the original structure of the algorithm but have the option to redefine or adjust certain steps. This pattern is designed to offer extensibility to the client developer.

Template Methods are frequently used in general purpose frameworks or libraries that will be used by other developer An example is an object that fires a sequence of events in response to an action, for example a process request. The object generates a ‘preprocess’ event, a ‘process’ event and a ‘postprocess’ event. The developer has the option to adjust the response to immediately before the processing, during the processing and immediately after the processing.

An easy way to think of Template Method is that of an algorithm with holes. It is up to the developer to fill these holes with appropriate functionality for each step.

Template method dofactory – link
Class code: Template method

Reflection in C#

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them

… full article

Class code: reflection demo #1
Class code: reflection demo #2

Template method + SQL + Reflection

Let’s try to build a generic mssql query using template method and reflection

Class code: MSSQL select
Class code: MSSQL select + generics + reflection

The next step will be to implement the Generic query into the template method pattern …

Links:

26 JAN 2020

singleton factory state recursion

designp

Design patterns are solutions to software design problems you find again and again in real-world application development. Patterns are about reusable designs and interactions of objects. The 23 Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral

Singleton pattern

The Singleton Pattern limits the number of instances of a particular object to just one. This single instance is called the singleton.

Singletons are useful in situations where system-wide actions need to be coordinated from a single central place. An example is a database connection pool. The pool manages the creation, destruction, and lifetime of all database connections for the entire application ensuring that no connections are ‘lost’.

Singleton dofactory – link
Class code: Singleton
Video: Singleton + design patterns intro [skip to 26:00]

Factory Method pattern

A Factory Method creates new objects as instructed by the client. One way to create objects is by invoking a constructor function with the new operator. There are situations however, where the client does not, or should not, know which one of several candidate objects to instantiate. The Factory Method allows the client to delegate object creation while still retaining control over which type to instantiate.

The key objective of the Factory Method is extensibility. Factory Methods are frequently used in applications that manage, maintain, or manipulate collections of objects that are different but at the same time have many characteristics (i.e. methods and properties) in common. An example would be a collection of documents with a mix of Xml documents, Pdf documents, and Rtf documents.

Factory Method dofactory – link
Class code: Factory method – simple
Class code: Factory method – advanced

Composite pattern

The Composite pattern allows the creation of objects with properties that are primitive items or a collection of objects. Each item in the collection can hold other collections themselves, creating deeply nested structures.

A tree control is a perfect example of a Composite pattern. The nodes of the tree either contain an individual object (leaf node) or a group of objects (a subtree of nodes).

All nodes in the Composite pattern share a common set of properties and methods which supports individual objects as well as object collections. This common interface greatly facilitates the design and construction of recursive algorithms that iterate over each object in the Composite collection.

Composite dofactory – link
Class code: Composite drawing app

State pattern

The State pattern provides state-specific logic to a limited set of objects in which each object represents a particular state. This is best explained with an example.

Say a customer places an online order for a TV. While this order is being processed it can in one of many states: New, Approved, Packed, Pending, Hold, Shipping, Completed, or Canceled. If all goes well the sequence will be New, Approved, Packed, Shipped, and Completed. However, at any point something unpredictable may happen, such as no inventory, breakage, or customer cancelation. If that happens the order needs to be handled appropriately.

Applying the State pattern to this scenario will provide you with 8 State objects, each with its own set of properties (state) and methods (i.e. the rules of acceptable state transitions). State machines are often implemented using the State pattern. These state machines simply have their State objects swapped out with another one when a state transition takes place.

Two other examples where the State pattern is useful include: vending machines that dispense products when a correct combination of coins is entered, and elevator logic which moves riders up or down depending on certain complex rules that attempt to minimize wait and ride times.

State dofactory – link
Class code: State – lightswitch

Recursion

a recursive definition is defined in terms of itself. Recursion is a computer programming technique involving the use of a procedure, subroutine, function, or algorithm that calls itself in a step having a termination condition so that successive repetitions are processed up to the critical step where the condition is met at which time the rest of each repetition is processed from the last one called to the first.

Sometimes a problem is too difficult or too complex to solve because it is too big. If the problem can be broken down into smaller versions of itself, we may be able to find a way to solve one of these smaller versions and then be able to build up to a solution to the entire problem. This is the idea behind recursion; recursive algorithms break down a problem into smaller pieces which you either already know the answer to, or can solve by applying the same algorithm to each piece, and then combining the results.

Recursion : geeks-for-geeks
Class code: Fibonacci w/o recursion

Time complexity

the time complexity is the computational complexity that describes the amount of time it takes to run an algorithm. Time complexity is commonly estimated by counting the number of elementary operations performed by the algorithm, supposing that each elementary operation takes a fixed amount of time to perform.

… full article

Sometime, time complexity in a recursive solution may be significantly larger than a non-recursive solution..,.

Links:

19-22 JAN 2020

react redux dist

react.png

react redux

React-redux makes it easier to pass these states from one component to another irrespective of their position in the component tree and hence prevents the complexity of the application.

When a react application holds various components in need of state from other components it becomes difficult to realize where the state should reside among these components to make it easier to maintain. React-redux provides a store which makes the state inside components easier to maintain. Along with stores, react-redux introduces actions and reducers which work simultaneously with stores to make the state more predictable. The working of the features in react-redux is explained below:

redux2

… full article

distribute react application

npm run build creates a build directory with a production build of your app. Inside the build/static directory will be your JavaScript and CSS files. Each filename inside of build/static will contain a unique hash of the file contents

… full article

another option will be to install react into visual studio, as explained here:

Using react inside visual studio

More topics covered:

Links:

15 JAN 2020

react route hoc

react.png

react router

React Router, and dynamic, client-side routing, allows us to build a single-page web application with navigation without the page refreshing as the user navigates. React Router uses component structure to call components, which display the appropriate information.
By preventing a page refresh, and using Router or Link, the flash of a white screen or blank page is prevented. This is one increasingly common way of having a more seamless user experience. React router also allows the user to utilize browser functionality like the back button and the refresh page while maintaining the correct view of the application.

react-router-dom
It contains the DOM bindings for React Router. In other words, the router components for websites

full example

High order component

A higher-order component (HOC) is an advanced technique in React for reusing component logic. Concretely, a higher-order component is a function that takes a component and returns a new component. Whereas a component transforms props into UI, a higher-order component transforms a component into another component.

… full article

More topics covered:

  • active css
  • cloudflare css
  • HOC: super-charge
  • card-content

Links:

12 JAN 2020

react css lifecycle ajax

react.png

CSS react

CSS Stylesheet:

csss2.PNG

csss1

Inline styling:

csss3.PNG

… full article

Component Lifecycle

lc.jpg

Each component has several “lifecycle methods” that you can use to run code at particular times in the process. Methods prefixed with will are called right before something happens, and methods prefixed with did are called right after something happens

Examples:

componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).

… full article

Ajax

You can use any AJAX library you like with React. Some popular ones are AxiosjQuery AJAX, and the browser built-in window.fetch.

You should populate data with AJAX calls in the componentDidMount lifecycle method. This is so you can use setState to update your component when the data is retrieved.

… full article

More topics covered:

  • Modify css each second
  • lifecycle – loops
  • fetch vs axios
  • ajax result to setState

Links:

 

01 JAN 2020!

react list add remove

react.png

Lists in react

use Array’s built-in map function to create a new array that has the same number of elements, and where each element is the result of calling the function you provide

list1.PNG

You might’ve noticed I used the item’s array index as the key prop in both examples above. This is actually not a great idea in all cases, and I’ll tell you why.

(The best choice for a key is an item’s unique ID, if it has one.)

React relies on the key to identify items in the list. Remember React uses a virtual DOM, and it only redraws the components that changed since the last render.

The first time a component like IdiomaticReactList is rendered, React will see that you want to render a bunch of items, and it will create DOM nodes for them.

The next time that component renders, React will say, “I already have some list items on screen – are these ones different?” It will avoid recreating DOM nodes if it can tell that the items are the same.

But here’s the important bit: React can’t tell with a simple equality check, because every time a JSX element is created, that’s a brand new object, unequal to the old one.

So that’s where the key prop comes in. React can look at the key and know that, yes, even though this <Item> is not strictly === to the old <Item>, it actually is the same because the keys are the same.

This leads to a couple rules for keys. They must be:

  • Unique – Every item in the list must have a unique key. So, person.firstName would be a bad choice, for example (might not be unique).

and

  • Permanent – An item’s key must not change between re-renders, unless that item is different. So, Math.random is a bad choice for a key (it’ll change every time… and it might not be unique (slim chance of that, though))

… full article

Container vs Presentational Components

conview.jpeg

The main thing to keep in mind is that container components and presentational components go together when setting up a React app component hierarchy. React apps will almost always need some components that take responsibility for the way things work, and components for displaying actual data. Where presentational components don’t manage state, container components do. Where presentational components are usually children in the app component hierarchy, container components are usually the parents of presentational components.

… full article

More topics covered:

  • list – condition
  • list – add
  • list – remove
  • pass functions as an arguments

Links:

 

Design a site like this with WordPress.com
Get started