Wednesday, November 07, 2018

It's not bad to use a wild card with a Java import statement.

In Clean Code, Robert C. Martin actually recommends using them to avoid long import lists.
Here is the recommendation (verbatim):
J1: Avoid Long Import Lists by Using Wildcards
If you use two or more classes from a package, then import the whole package with
import package.*;
Long lists of imports are daunting to the reader. We don’t want to clutter up the tops of our modules with 80 lines of imports. Rather we want the imports to be a concise statement about which packages we collaborate with.
Specific imports are hard dependencies, whereas wildcard imports are not. If you specifically import a class, then that class must exist. But if you import a package with a wildcard, no particular classes need to exist. The import statement simply adds the package to the search path when hunting for names. So no true dependency is created by such imports, and they therefore serve to keep our modules less coupled.
There are times when the long list of specific imports can be useful. For example, if you are dealing with legacy code and you want to find out what classes you need to build mocks and stubs for, you can walk down the list of specific imports to find out the true qualified names of all those classes and then put the appropriate stubs in place. However, this use for specific imports is very rare. Furthermore, most modern IDEs will allow you to convert the wildcarded imports to a list of specific imports with a single command. So even in the legacy case it’s better to import wildcards.
Wildcard imports can sometimes cause name conflicts and ambiguities. Two classes with the same name, but in different packages, will need to be specifically imported, or at least specifically qualified when used. This can be a nuisance but is rare enough that using wildcard imports is still generally better than specific imports.

Saturday, February 21, 2015

Service-Oriented Architecture (SOA) : 9 Principles of Service Design

Introduction

Service-Oriented Architecture (SOA) is a specific design approach to building a system based on recognizably different pieces of software providing application functionality as services to other applications and/or services via standard Protocols 1.

The Open Group's definition of SOA:
Service-Oriented Architecture is an architectural style that supports service-orientation. Service-orientation is a way of thinking in terms of services and service-based software development and the outcomes of services.
A service:

  • Is a logical representation of a repeatable business activity that has a specified outcome (e.g., check customer credit, provide weather data, consolidate drilling reports)
  • Is self-contained.
  • May be composed of other services
  • Is a “black box” to consumers of the service.
From the definitions above, it should be clear that SOA is primarily about services.

So, what is a service?
Within a SOA environment,  a service is a piece of software that provides some useful functionality to clients. A service is comprised of a set of well-defined elements, namely: contract, interface, and implementation.

  • The contract element specifies what clients can expect from a service based upon their anticipated needs, and what a service provider needs to offer. 
  • The interface element defines how clients can make use of the service. 
  • The implementation element is the actual realization of the service. 
  • Typically, the contract and interface elements are visible to the outside world, but the implementation is more a black box to clients.

The service must be well design around these three elements (contract, interface and implementation) to make it clear for all clients to ascertain: what value the service offers, how much it costs to use the service and most importantly how to use the service.

In this article I outline some general steps/actions in designing services and then take a look at nine key principles of service design in a SOA environment.

Steps in Designing Services

Below are the main steps/actions in designing services in SOA.
  1. Define the functionality/capabilities that the service offers
  2. Design the service  interface
    1. Design the operations and the functionality the operations offer.
    2. Design the parameters of the operations.
    3. Design the return value or the effect of the operation.
    4. Design test cases for the operations.
  3. Design the service contract 
    1. Define who is allowed to use the service and who can use what operation.
    2. Decide how often the service is available.
    3. Define the load the service should be able to handle.
    4. Define other relevant quality of service attributes.
  4. Design the service implementation
    1. Decide what tool, language or framework to use for the implementation.
    2. Design the components needed for the implementation.
    3. Decide what tools to use to test the implementation.
While executing these steps/actions, there are  several basic service design principles that should be adhered to and followed. These principles are covered in the next section.

9 Principles of Service Design

Service design principles indicate what attributes a service should have in order to be a usable building block in the SOA environment. Services that are poorly designed or implemented, in the overall architecture, will be of little value for the client. Utilizing solid service design principles will help to create a service that is useful, reusable, and help service client to judge if the services are well designed.

The following sections lists nine service design principles that should be considered when designing/creating services.  The importance of each principle depends on the nature and need of the enterprise creating the service. These principles covers both technical and non-technical aspects of service design. Now lets look into these nine principles:

1. Provide value

  • A service should provide value. 
  • For every service, consider if and why it is needed. 
  • If a service doesn't provide value to someone or something - organization's clients, internal departments, other IT systems, and so on -  then it is probably not a good service, or only part of a service and not a service by itself.

2. Meaningful

  • A service should be meaningful. 
  • It should be easy for (future) clients to use a service. 
  • The service interface needs to be meaningful to the clients and not too abstract or complex.
  • If a service is not meaningful, the required effort to consume a service will increase.
  • If a service is not meaningful clients will not be able or are reluctant to use such services since they don't understand them or it is too expensive or difficult to use and integrate them into their applications or services.

3. Implementation hiding

  • A service should hide its implementation. 
  • Clients don't care about the actual implementation behind the service; this should be a black box for them. 
  • Clients focus on the contract and interface of a service to decide whether to use it and to be able to actually consume it. 
  • A service and its interface and contract, should be self-describing and understandable.
  • Hiding the service implementation details is crucial in a SOA environment in which there are differentiation between contract, interface, and implementation. 
  • The service interface should abstract away or hide the specifics of the underlying technologies and systems that do the actual work. 
  • Implementation hiding makes it easier to change, upgrade, or swap the implementation without breaking interoperability since the interface can stay the same. 
  • Implementation hiding doesn't burden clients with the need to know about the specifics of the implementation in order to utilize the service.

4. Trust

  • A service needs to provides a high level of trust i.e. confidence in the reliability of the service.
  • Clients need to have confidence in the service they consume. 
  • Clients want services to be accurate. 
  • Services should do what they are supposed to do, especially in a SOA environment where services can be outside your own span-of-control in case of external services. 
  • Important factors in trust are applying sufficient security, fault-prevention and handling, and auditing capabilities to the services to increase trust.
  • Security of the Service
    • Apply message-level security like signing and encryption of messages to provide end-to-end security from the client to provider when passing sensitive data. 
    • Explicitly state security in the service contracts so providers and clients know and agree on the level of security that is provided.
    • Security is part of the way that services are accessed and provided and so it is part of the service interface. For example, if a service is accessed over SSL/TLS, it needs to be defined if the service input and service output require signing. 
    • The security of a service should be based on recognized standards especially when interoperability is a requirement.
  • Fault Prevention and Fault Handling of the Service  
    • Faults can be seen as situations in which the outcome or effect of a service invocation is different than the 'happy path flow'. 
    • Fault handling and prevention should be implemented at the level of services and operations, as is the case for security.
    • Services need to deal with the different types of faults differently. The types of faults are:
      • Business faults: Expected faults that have meaning to the clients: a failure to meet a particular business requirement.
      • Faulty user input: Faults in the input of service operations so operations are unable to execute correctly or have an undesired outcome.
      • Technical and software faults: Unexpected and undesired failures that cannot be easily recovered from by clients such as a network failures, software programming errors, and corrupt disks.

5. Idempotent

  • Service operations should be Idempotent. 
  • An idempotent operation is one that has no additional effect if it is called more than once with the same input parameters.
  • A service should be predictable; invoking a service operation with the same input more than once should result in the same outcome.
  • Idempotency can be broken when service clients are dependent on a particular instance of a service with or without knowing this dependency. This is mostly the case for services that are stateful, meaning a service instance maintains state (data) that is specific to a particular client.
  • Services should either be stateless or the state should be accessed and persist in a shared datastore, so it is accessible and the same for all instances of a service to guarantee idempotency.

6. Isolation

  • A service should strive for isolation.
  • Isolation means that an operation that is invoked by a client does not rely on the same client to have to invoked other operations prior or after its own invocation to deliver the promised functionality. 
  • Services only provide flexibility and can only be easily changed if their operations are independent of other operations within the same or another service; this is called isolation. 
  • If a change to an operation results in changes to several other operations that are tightly coupled to the original changed operation, then the service is not flexible. 
  • Service operations need to be separate building blocks that provide capabilities within  themselves.
  • It is very important from a client perspective that operations of services are self-sufficient. 
  • This principle is also known as "loose-coupling" or "decoupling", as opposed to operations that are tightly coupled to other operations, either in the same service or another service.
  • Clients want to invoke only one operation to achieve what is agreed upon in the service contract for that operation, they don't want to be burdened with the task of invoking other operations to make the actual operation function properly.

7. Interoperable

  • Services should be interoperable. 
  • Interoperability is a measure for the amount of effort it takes to use and invoke services.
  • Services should be easy to integrate into the overall SOA landscape.  
  • Interoperability is achieved by using standards for describing, providing, and accessing services such as JSON, XML, WS-*, WADL, and WSDL. 
  • The use of standards increases the ease of consuming services since most platforms and vendors adhere to such standards. 
  • Only the service interface needs to be interoperable; the implementation itself can be proprietary. 
  • Interoperability is less of a concern when SOA is applied within your own organization consisting of a homogeneous environment in which you have standardized on one or a few platforms and open-source technologies.

8. Granularity

  • A service granularity should to be carefully considered.
  • Service Granularity is a design principle that identifies the optimal scope of business functionality in a service operation.2
  • Services are of different importance based on the degree of value or functionality they add. 
  • Differentiate vertically, based on functionality, providing a limited and independent set of capabilities exposed by operations that belong together.
  • Divide functionality in externally visible portions vertically before thinking how services are internally implemented in horizontal layers. 
  • Service granularity should also be reflected in the release management process that is responsible for promoting IT assets through development, QA/Test, and production environments. 
    • The granularity of releases in a SOA environment is based on the services that are release vertically, per services, instead of big horizontal releases that impact several services at once. 
    • Release per service makes release management easier since the impact of a release is small (has little impact on other systems and services). 
    • Release per service makes sure the focus is on releasing functional building blocks that are useful to clients instead of releasing based on technology (for example a complete horizontal layer) with less value and meaning to clients.
  • How granular should a service and its operations be? A service should be:
    • Big enough to provide value on its own. For example: a setProfile operation maybe too small since it provides no value in itself.
    • Small enough to be able to change, without changing the whole IT landscape in the department or organization. For example: Putting all ERP-related functionality in one big monolithic service with thousands of operations that are used by almost everyone is too big, since every change in ERP-related functionality requires a change in this one service.
  • Granularity should be derived from functionality. 
    • Functionalities that are unrelated should not be mix into a single service and 
    • Functionalities that belongs together should not be put into different services.
  • Granularity should go hand-in-hand with transaction boundaries. 
    • An operation defines a transactional unit. 
    • All activities as part of an operation are either successfully executed and committed together or
    • All activities as part of the operation are rolled back, in case an operation fails.

9. Reusability

  • A service should strive for Reusability, but not over-Generification 
  • Reusability means a service is used by more than one client or is meant to be used by more than one client in the future. 
  • A service may be designed with reuse in mind, but has not yet been used by more than one client.
  • The client of a service is the actual application, process, organizational unit, customer, or organization that uses a service. 
  • Typically, the more a service is reused the less flexible it often becomes. An increase in the number of clients results in more wishes and requirements that need to be agreed upon by all stakeholders. Therefore, there is additional need to analyze whether changes to the service to meet requirements for one client, impact other clients.
  • Often the more added value a service delivers, the more specific it is and the less reusable it becomes, and vice versa. 
    • Business services tend to add a lot of value, and are not very reusable, 
    • Elementary services are very reusable but are not as valuable. 
    • Composite services offer something in between.
  • Don't  make services more generic to increase their reusability. 
    • A service that is too generic is much harder to understand and use. 
    • First investigate if (future) reusability is necessary, before you end up with over-generic and non-understandable services and operations. 
  • Avoid creating over-generic  and non-specific services. 
    • Service clients don't know how to handle an over-generic service such as: SuperService.doThings, even though it is very reusable. 
    • An over-generic service requires too much knowledge of the implementation of the service in order to be able to use it correctly.
  • Reusability is different from ease-of-use or usability of services. 

Summary

In this article, I provide a brief outline of the typical steps in Designing Services and 9 basic Design Principles to guide service design in a SOA environment. The 9 SOA Service Design Principles covered are: Provide value, Meaningful, Implementation Hiding, Trust, Idempotent, Isolation, Interoperable, Granularity and Reusability. 

Adhering to these basic design principles will result in good services that are meaningful, provide value, easy to use, reusable and  flexible (but not over-generic),  and can be relied upon (trust) by clients.  Not all services have the same relevance, therefore in designing services in a SOA environment, the services must be categorized and different principles and guidelines should be apply to different types of services.


Additional References:
SOA Made Simple by Lonneke Dikmans and Ronald van Luttikhuizen
SOA Patterns by Arnon Rotem-Gal-Oz 


Saturday, March 15, 2014

Techniques and Strategies to Break-up Large Classes

Introduction
Typically, features are added to software systems as little tweaks. This usually involves adding a little code to existing methods and/or adding a few more methods to existing classes. It is very tempting to just make the changes to existing classes, because at first glance it seems easier to just add the code to an existing class. 

This seemingly 'easier' way of making changes can lead to serious problems such as:
  1. When you keep adding code to existing classes, you end up with very long methods and large classes. 
  2. The software turns into a swamp. 
  3. It takes a long time to understand how old features work.
  4. It takes more time to understand how to add new features.
This article highlights some of the problems with large classes, explain why they should be avoided and techniques/tactics to break-up an existing LARGE class and get it under unit tests.

Problems with Large Classes
What are the problems with big classes?

1). Large classes cause confusion.

  • If a class contains 50 or 60 methods, it is difficult to get a sense of what you have to change and whether it is going to affect anything else. 
  • If a class have lots of instance variables, it's hard to know what the effects are of changing a variable. 

2). Large classes cause problem with task scheduling

  • If a class has 20+ responsibilities, then more than likely it will have to be changed while adding features.
  • Several programmers maybe adding different features and have to work in the same huge class with 20+ responsibilities. 
  • If they work concurrently on the same huge class, this can lead to serious trashing and code conflicts. 

3). Big Classes are difficult to test 

  • Classes that are too big, often hide too much.
  • Encapsulation is good when it helps us reason about code. But when we encapsulate too much in a single class, the stuff inside rots and festers. 
  • There is no easy way to sense effects, so developers fall back to "Edit and Pray" programming. In this case changes will end up taking too long or bug counts increases. 
  • You will pay for the lack of clarity typically in big classes. 

How to Make Changes without Making a Big Class worse
Confront with a big class, how can the you make changes and add features without making things worse?

1). Use Sprout Class and Sprout Method techniques: 

  • When you have to make changes, you should consider putting the code into a new class or method. 
  • Sprout Class really keep things from getting worse. 
  • Sprout Method involves adding code to the existing big class, but it is also identifying and naming another thing that the class does. Later this can help to pull those methods into smaller classes. 

2). The key remedy for big classes is refactoring. 

  • You can breakdown big classes into a set of smaller classes. 
  • You will need to figure out what the smaller classes should look like. 

3). Use Single-Responsibility Principle (SRP).

  • Use SRP to figure out what the smaller classes should look like.
  • SRP states that, every class should have a single responsibility. Each class should have a single purpose in the system.
  • There should be only one reason to change a class. 
  • SRP defines the "main purpose" of the class. 

4). How to Find class responsibilities. 

  • The name of a class should give an indication of its responsibility. 
  • Look at method names and see if there is a natural way to group the names of methods. 
  • Identify entry points to the class. 
  • Big class usually means that the class have too many responsibilities. 
  • In the real-world of big classes, the key is to identify the different responsibilities and then figure out a way to incrementally move toward more focused and smaller classes each with a Single Responsibility. 

5). Identifying Responsibilities within a class.

  • Ask the questions :  "Why is this method here?" and    "What is it doing for the class?"
  • Use "Group Methods" technique to grouped the methods based on the answers to the questions in a list, putting together methods that have similar reasons to be in the class. 
  • Learning to identify responsibilities is a Design Skill. It take practice. 
  • Learn how to identify responsibilities and how to separate them well. 
  • Legacy code offers more possibilities for the application of design skills , than new features do. 
  • You can reason about design trade-offs when you see the code that will be affected. 
  • It is easier to see whether structure is appropriate in a given context because the context is real and there in front of you. 
  • In identifying responsibilities in big a class, you are not inventing them, you are just discovering what is already there in the class. 
  • All code does identifiable things - no matter how bad the code is. Sometimes it will be hard to identify what the code does, but there are techniques that can be used to help. 
  • The more you start noticing the responsibilities inherent in the code, the more you learn about it. 

Techniques for Identifying Responsibilities in Existing Code 

1). Group Methods 

  • Look for similar methods in the code. 
  • Write down all the methods on a class including the access type. 
  • Find methods that seems to go together and group those. 
  • You don't have to categorize all of the methods into new classes. Instead you should just find methods that look like they are part of a common responsibility. 
  • Wait until you have to make a change to a method you have categorized and then decide if you should  extract a new class or not. 
  • Put up poster of big classes with lots of methods and have team members see if they can group the methods over time. 

2). Look at Hidden Methods

  • Pay special attention to private and protected methods. 
  • If a class has many private and or protected methods, it often indicates that there is another class in the class dying to get out! 
  • Big classes can hide a lot. 
  • In general, if you have to test a private method, the method shouldn't be private. 
  • If making the method public bothers you chances are it is because it is a part of a separate responsibility and should be in another class.  

3). Look for Decisions that Can Change 

  • Look for decisions that you have already made. 
  • Is there some way of doing something (e.g. Connecting to a database, or web service,...) that seems hard-coded. if so, can this be changed. 
  • Paying attention only to the name of a method doesn't tell the full story. 
  • Big classes tend to contains methods that does things at various levels of abstraction. These methods does more than one thing. 
  • In such cases, you should do a little extract method refactoring before really settling on classes to extract. 
  • What method to extract, can be determined by looking at how many things are assumed in the big methods code. 
  • Is the code calling methods from a particular API? Is the code assuming it will always be accessing the same database?
    • if so, then extract methods that reflect what you intend at the higher-level. 
    • if you are getting information from a database, then extract a method Named after the information it is getting. 
    • These extractions can lead to many methods, but method grouping will be easier 
    • Often resources are completely encapsulated behind a set of methods. 
    • When you extract class from them, you'll have broken some dependencies on low-level details. 

4). Look for Internal Relationships

  • Look for relationships between instance variables and methods. 
    • Ask questions like, are certain instance variables used by some methods and not others? 
    • Very few classes have methods that all use all instance variables. 
    • Usually there is some sort of lumping of methods and instance variables. 
    • Two or three methods might be the only ones that use a set of three variables. 
    • Often the method names will help you to see these relationships.
  • Use "feature sketches" diagrams to make sketch of the relationships inside a class. To create feature sketch diagram:
    • Draw a circle for each instance variables.
    • Draw a circle for each method. 
    • Draw a line from each method circle to the circles of any instance variables and methods that it accesses or modifies. 
    • Add an arrow on the line that point in the direction of a method or variable that is used by another method or variable. 
    • Skip the constructors. 
    • Draw a big circles around the set of variables and methods with lots of connections. Typically, these are candidate for new classes.
    • Before creating a new class, figure out whether the new class has a good, distinct responsibility and can be named. 

5). Look for the Primary Responsibility 

  • Try to describe the responsibility of the class in a single sentence. 
  • Remember that SRP says "a class should have a single responsibility". 
  • Therefore this single responsibility should be easy to write down in a single sentence. 
  • Apply this technique to a big class in your current system. 
    • As you think about what a client need from the class, add clauses to the sentence. E.g. The class does this, and this, and that, etc... 
    • Is there any one thing that seems more important than anything else. If so, then this could be the key responsibility of the class 
    • The other responsibilities should be factored out into other classes. 
  • SRP can be violated at the interface and implementation levels. 
    • SRP is violated at the interface level, when a class presents an interface that makes it appear that it is responsible for a very large number of things. 
    • SRP is violated at the implementation level, when the class have more than a single responsibility. 
  • The focus should be more on SRP violation (avoidance) at the implementation level.
    • Is the class really handling that many responsibilities or 
    • Is it just delegating to other classes to do the work. 
    • If it is just delegating then we don't have a large monolithic class; we just have a facade, a front end for several little classes, which can be manage easier. 
  • Apply the Interface Segregation Principle (ISP).
    • ISP is a technique of making an interface for grouping of methods in a big class for a particular set of clients. 
    • When a class is very large, rarely do all its clients use all of its methods. 
    • Particular clients tends to use different grouping of methods. 
    • If we create an interface for these groupings, then each client can see the 'big class' through that particular interface. 
    • This helps to hide information and also decreases dependency in the system. 
    • The clients no longer have to recompile whenever the big class does. 
    • When there are interfaces for particular sets of clients, code can be move from the big class to a new class that uses the original class. 
  • Be careful, applying ISP refactoring is harder than it sounds. 
    • More methods must be exposed in public interface of the original big class, so that the new class will have access to everything it needs to work. 
    • Client code has to be changed to use the new class rather than the old big one.
    • To do so safely, tests must be around those clients. 
    • However, refactoring using ISP, helps to whittle away at the interface of a big class. 

6). When All Else Fails, Do Some Scratch Refactoring

  • If you are having a lot of trouble seeing responsibilities in a class, do some "scratch refactoring".
  • Remember the things seen when you scratch are not necessarily the things you'll end up with when you refactor. 

7). Focus on the Current Work 

  • Pay attention to what (the new feature, bug fix, etc) you have to do right now. 
  • If you are providing a different way of doing anything, you might have identified a responsibility that you should extract and then allow substitution for. 
  • It easy to become overwhelmed by the number of distinct responsibilities you can identify in a class. 
    • The changes that you are currently making are telling you about some way that the software can change. 
    • Often just recognizing that way of changing is enough to see the new code you write as a separate responsibility. 

8). Other Techniques 

  • Read more books about design patterns.
  • Look at other programmer's code. Take some time to browse and see how other people are doing things.
  • Look at open-source projects.
  • Pay attention to how classes are named and the correspondence between class names and the names of methods. 
  • Over time you'll get better at identify hidden responsibilities and start to see them when you browse unfamiliar code. 

Moving Forward After Identifying all the Responsibilities in a Big Class 
After identifying all the responsibilities in a big class, how do you move forward? Should you take a week and start to whack at the big classes in the system? Should you break them down into little bits? To answer these questions use the following strategies and tactics:
1). Strategies
  • Usually large 'refactoring binge' leads to system stability breakdown for a little while ( even with unit tests in place). 
    • If it is early in the release cycle, then  refactoring binge can be fine. 
    • But, don't let the bugs dissuade you from other refactoring. 
  • The best approach to breaking down big classes is to:
    • Identify the responsibilities. 
    • Ensure all team members understands the responsibilities.
    • Break down the class on an as-needed basis. This helps to spreads out the risk of the changes. 
2). Tactics 
  • Often when breaking up large classes, at the beginning SRP can only be applied at the implementation level. 
    • In these cases simply start by Extracting classes from big classes and delegate to them. 
  • Introducing SRP at the interface level requires more work. 
    • The client of the class must change 
    • Tests must be written for them. 
  • The tactics to extract classes from a big class depends on certain  factors:
    • How easy it is to get tests around the methods that could be affected? 
    • Take a look at the class and list all of the instance variables and methods that you'll have to move.
    • That list should give you an idea of what methods you should write tests for. 
  • If you can get tests in place, you can extract class in a very straightforward way using Extract Class refactoring. 
  • If you are not able to get tests in place, then move forward using a more conservative approach, outline in the following steps:
    1. Identity a responsibility that you want to separate into another class. 
    2. Figure out whether any instance variables will have to move to the new class. 
      • if so move them to a separate part of the class declaration (the "Moving Section"), away from other instance variables.  
    3. Extract bodies of whole methods to be moved to the new class to new methods. 
      • The name of each method should be the same as its old name, but with a unique common prefix eg. "MOVING"
      • Make sure to "preserver signatures" for these methods. 
      • Put the extracted methods in that section of the class next to the variables you are moving. 
    4. If only parts of the methods should be moved, then extract them from the original methods.
      • Use the prefix MOVING again for their names.
      • Put them in the separate "moving section" of the class.
    5. Review the "Moving Section" of the class containing variables and methods to be moved. 
      • Do a text search of current class and subclasses to make sure that none of the variables that you are going to move is used outside of the methods you are going to move. 
      • DO NOT depend on the compiler, because of problems with variable shadowing. 
    6. Move All instance variables and methods in the "moving section" directly to the new class. 
      • Create an instance of the new class in the old big class.
      • Rely on the compiler to find places where the moved methods have to be called on the new instance rather than the old class. 
    7. After completing the move and the code compile then remove the prefix "MOVING" from method names. 
      • Lean on the compiler to navigate to the places where you need to change the names. 
  • These steps are very involved, but necessary if you are in very complex and tangled code and you want to extract classes without tests in place. 
  • Extracting classes without test, can cause: 
    • Subtle bugs related to inheritance ( and method overriding).
    • If you move a method that overrides another method in a base class, the compiler will not complain. Callers of that method on the original big class will simple call the method with the same name in the base class. 
    • A variable in a subclass can hide a variable with the same name in the superclass, so moving the variable from the subclass will make the hidden variable visible. 
  • To get around method override problems: you don't move the original method at all. You create new methods by extracting only the body, but leave the actually method in place in the big class. 
  • To get around variable shadowing: do a manual text search for usage of the variables before you use them. Remember to Just be careful. 
  • When breaking down large class into smaller testable classes:
    • Be careful not to get too over-ambitious. 
    • Remember the existing structure in place in the big class works. 
      • It supports the functionality.
      • It just might not be tuned towards moving forward and adding new features. 
    • Sometimes the best thing that you can do is formulate a view of how a large class is going to look after refactoring and then just forget about it. 
      • You did it to discover what is possible. 
    • Be sensitive to what is there and move accordingly, not necessarily an ideal design, but at least in a better direction. 


REFERENCES:

Monday, January 20, 2014

Advantages of Python Programming Language

String Indexing or subscripting

Python is a widely used general-purpose, high-level programming language. 
Advantages of Python:
  • Python is easy and fast to learn. 
  • Python's syntax is clear and readable.
  • Python's syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C. 
  • Python provides constructs intended to enable clear programs on both a small and large scale.
  • Python's design philosophy emphasizes code readability.
  • Simple to get support.
  • Fast to Code, i.e. it is easier and faster to code a problem in Python than in C, C++ or Java, just to mention a few other languages.
  • Python is portable, i.e. it runs on multiple platforms and systems, like e.g. Linux and Microsoft Windows.
  • Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. 
  • Python features a dynamic type system and automatic memory management and has a large and comprehensive standard library.
  • Python is trendy, i.e more and more successful companies switch to Python, like Google did a long time ago.

Thursday, January 09, 2014

The Ten Commandments of Egoless Programming

The Ten Commandments of Egoless Programming, as originally established in Jerry Weinberg's book The Psychology of Computer Programming:

  1. Understand and accept that you will make mistakes. The point is to find them early, before they make it into production. Fortunately, except for the few of us developing rocket guidance software at JPL, mistakes are rarely fatal in our industry, so we can, and should, learn, laugh, and move on.
  2. You are not your code. Remember that the entire point of a review is to find problems, and problems will be found. Don't take it personally when one is uncovered.
  3. No matter how much "karate" you know, someone else will always know more. Such an individual can teach you some new moves if you ask. Seek and accept input from others, especially when you think it's not needed.
  4. Don't rewrite code without consultation. There's a fine line between "fixing code" and "rewriting code." Know the difference, and pursue stylistic changes within the framework of a code review, not as a lone enforcer.
  5. Treat people who know less than you with respect, deference, and patience. Nontechnical people who deal with developers on a regular basis almost universally hold the opinion that we are prima donnas at best and crybabies at worst. Don't reinforce this stereotype with anger and impatience.
  6. The only constant in the world is change. Be open to it and accept it with a smile. Look at each change to your requirements, platform, or tool as a new challenge, not as some serious inconvenience to be fought.
  7. The only true authority stems from knowledge, not from position. Knowledge engenders authority, and authority engenders respect – so if you want respect in an egoless environment, cultivate knowledge.
  8. Fight for what you believe, but gracefully accept defeat. Understand that sometimes your ideas will be overruled. Even if you do turn out to be right, don't take revenge or say, "I told you so" more than a few times at most, and don't make your dearly departed idea a martyr or rallying cry.
  9. Don't be "the guy in the room." Don't be the guy coding in the dark office emerging only to buy cola. The guy in the room is out of touch, out of sight, and out of control and has no place in an open, collaborative environment.
  10. Critique code instead of people – be kind to the coder, not to the code. As much as possible, make all of your comments positive and oriented to improving the code. Relate comments to local standards, program specs, increased performance, etc.
References:
The Psychology of Computer Programming by Gerald M. Weinberg (September 1998Anl Sub). This landmark 1971 classic is reprinted with a new preface, chapter-by-chapter commentary, and straight-from-the-heart observations on topics that affect the professional life of programmers.

Tuesday, December 10, 2013

The Grass isn't really much Greener in Green-field Software Development.

"It is fun to build systems from scratch, but frankly green-field systems have their own set of problems1." 

The Typical Scenario:
An existing system becomes murky and hard to change over time. People in the organization get frustrated with how long it takes to make changes in it. They move their "best" people and sometimes their trouble-makers onto a new team that is charged with the task of "creating the replacement system with a better architecture". 


In the beginning, everything is fine. They know what the problems were with the old architecture, and spend some time coming up with a new design. In the meantime, the rest of developers are working on the old system. The system is in service, so they receive requests for bug fixes and occasionally new features. The business looks soberly at each new feature and decides whether it needs to be in the old system or whether the client can wait for the new system. In many cases, the client can't wait, so the change goes into both.


The green-field team has to do double duty, trying to replace a system that is constantly changing.  As the months goes by it becomes clearer that they are not going to be able to replace the old system (the system you're maintaining), any time soon . The pressure increases. They work days, nights and weekends. In many cases, the rest of the organization discovers that the work that you are doing is critical and that you are tending the investment that everyone will have to still rely on in the near future2.



References:

Thursday, June 20, 2013

TrueNotes Notepad Android App Published on Google Play Store

Finally, the long awaited TrueNotes Notepad Android Mobile Application is available in the Google Play Store. 

TrueNotes Notepad is very easy to use and offers awesome and unique features (e.g. Voice recognition) aimed at making notes taking while on-the-go a very simple, pleasant and delightful experience for users. 

Key features of the app includes: 
  • Add note entries via Voice or Typing. Add as many note entries as you want. 
  • Unique Lined Note Editor/View screen - just like paper ruled yellow notepad. 
  • Edit, View and Delete note entries on the fly. 
  • Email notes directly from the Details/Edit screen. 
  • Startup screen showing a list of all note entries. 
  • Fast Searching and Filtering of notes by keywords in the title or details. 
  • Easy navigation of notes on the Details/Edit screen. 
  • And lots more features ... 
So, Download and tryout TrueNotes Notepad application today !!

Monday, June 17, 2013

ABC TrueSpell Android App Published on Google Play Store

The awesome ABC TrueSpell Android App is now available in the Google Play Store. 

ABC TrueSpell is a unique flip spelling guide for children to learn the Alphabet and how to spell common three letter words, at their own pace. 

But, how it works? It's simple !

ABC TrueSpell displays colorful pictures and voice prompt you to spell the words. You flip through the stack of letters (by swiping left or right) until you have spelled the word. When you spell the word correctly, look and listen for the surprise !

In the preference settings, you can choose to:- 
  • Display the pictures in alphabetical order or randomly, 
  • Enable or disable voice prompts/hints and 
  • Display the letters in uppercase or lowercase. 
The app was designed and developed primarily for Android 7" Tablets, but should works fine on Android 10" Tablets and Phones running:  Android 4.0.3 Ice Cream Sandwich (API level 15) and newer versions. 

Get ABC TrueSpell today on Google Play Store and post your comments/reviews !!

Wednesday, June 27, 2012

Test-Driven Development

Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes a failing test case that defines a desired improvement or new feature, then produces code to pass that test and finally refactors the new code to acceptable standards.

Test-driven development cycle
1. Add a test
In test-driven development, each new feature begins with writing a test. This test must inevitably fail because it is written before the feature has been implemented. (If it does not fail, then either the proposed “new” feature already exists or the test is defective.) To write a test, the developer must clearly understand the feature's specification and requirements. The developer can accomplish this through use cases and user stories that cover the requirements and exception conditions. This could also imply a variant, or modification of an existing test. This is a differentiating feature of test-driven development versus writing unit tests after the code is written: it makes the developer focus on the requirements before writing the code, a subtle but important difference.

2. Run all tests and see if the new one fails
This validates that the test harness is working correctly and that the new test does not mistakenly pass without requiring any new code. This step also tests the test itself, in the negative: it rules out the possibility that the new test will always pass, and therefore be worthless. The new test should also fail for the expected reason. This increases confidence (although it does not entirely guarantee) that it is testing the right thing, and will pass only in intended cases.

3. Write some code
The next step is to write some code that will cause the test to pass. The new code written at this stage will not be perfect and may, for example, pass the test in an inelegant way. That is acceptable because later steps will improve and hone it. It is important that the code written is only designed to pass the test; no further (and therefore untested) functionality should be predicted and 'allowed for' at any stage. Run the automated tests and see them succeed If all test cases now pass, the programmer can be confident that the code meets all the tested requirements. This is a good point from which to begin the final step of the cycle.

4. Refactor code
Now the code can be cleaned up as necessary. By re-running the test cases, the developer can be confident that code refactoring is not damaging any existing functionality. The concept of removing duplication is an important aspect of any software design. In this case, however, it also applies to removing any duplication between the test code and the production code — for example magic numbers or strings that were repeated in both, in order to make the test pass in step 3.

5. Repeat
Starting with another new test, the cycle is then repeated to push forward the functionality. The size of the steps should always be small, with as few as 1 to 10 edits between each test run. If new code does not rapidly satisfy a new test, or other tests fail unexpectedly, the programmer should undo or revert in preference to excessive debugging. Continuous Integration helps by providing revertible checkpoints. When using external libraries it is important not to make increments that are so small as to be effectively merely testing the library itself,[3] unless there is some reason to believe that the library is buggy or is not sufficiently feature-complete to serve all the needs of the main program being written.

Friday, August 07, 2009

Programming Scala

Programming Scala introduces an exciting new language that offers all the benefits of a modern object model, functional programming, and an advanced type system. Packed with code examples, this comprehensive book teaches you how to be productive with Scala quickly, and explains what makes this language ideal for today's highly scalable, component-based applications that support concurrency and distribution. You'll also learn the advantages that Scala offers as a language for the Java Virtual Machine. Read More...

Friday, July 03, 2009

Java BlockingQueue and threading

A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

A BlockingQueue does not accept null elements. Implementations throw NullPointerException on attempts to add, put or offer a null. A null is used as a sentinel value to indicate failure of poll operations.

A BlockingQueue may be capacity bounded. At any given time it may have a remainingCapacity beyond which no additional elements can be put without blocking. A BlockingQueue without any intrinsic capacity constraints always reports a remaining capacity of Integer.MAX_VALUE.

BlockingQueue implementations are designed to be used primarily for producer-consumer queues, but additionally support the Collection interface. So, for example, it is possible to remove an arbitrary element from a queue using remove(x). However, such operations are in general not performed very efficiently, and are intended for only occasional use, such as when a queued message is cancelled.

BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example, for addAll(c) to fail (throwing an exception) after adding only some of the elements in c.

A BlockingQueue does not intrinsically support any kind of "close" or "shutdown" operation to indicate that no more items will be added. The needs and usage of such features tend to be implementation-dependent. For example, a common tactic is for producers to insert special end-of-stream or poison objects, that are interpreted accordingly when taken by consumers.

Usage example, based on a typical producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers.

class Producer implements Runnable {
private final BlockingQueue queue;
Producer(BlockingQueue q) { queue = q; }
public void run() {
try {
while(true) { queue.put(produce()); }
} catch (InterruptedException ex) { ... handle ...}
}
Object produce() { ... }
}

class Consumer implements Runnable {
private final BlockingQueue queue;
Consumer(BlockingQueue q) { queue = q; }
public void run() {
try {
while(true) { consume(queue.take()); }
} catch (InterruptedException ex) { ... handle ...}
}
void consume(Object x) { ... }
}

class Setup {
void main() {
BlockingQueue q = new SomeQueueImplementation();
Producer p = new Producer(q);
Consumer c1 = new Consumer(q);
Consumer c2 = new Consumer(q);
new Thread(p).start();
new Thread(c1).start();
new Thread(c2).start();
}
}

Taken from Here

Friday, May 15, 2009

Programming in Scala

I am currently reading the new book "Programming in Scala" by Martin Odersky, Lex Spoon and Bill Venners. So, far I have found this book to be a pretty interesting read. It has held my attention for long spells. To motivate myself even more I have decided to share whatever I learn from this book in this blog. So stay tune and check back soon for the real action...

Sunday, August 03, 2008

Is Java ripe for replacement?

With the recent reports of Java™'s imminent demise, you're probably wondering if it's time to leave the platform behind for greener pastures. Before you make a decision, step back and examine the Java ecosystem, along with that of its competitors, to see if the rumors have any substance. It's time, in other words, to have a State of the Java Union address, holding neither pride nor prejudice in the evaluation of the platform.
Is Java ripe for replacement?

Parleys.com - The Next Generation RIA eLearning Platform

Parleys - The Next Generation RIA eLearning Platform
Very interesting technology based presentation combining Audio, Video and Slides. A broad range of current and emerging technologies are covered by experts in the field.

Tuesday, July 29, 2008

Scala and XML

Scala is a popular new programming language that runs on the Java™ Virtual Machine (JVM.) Scala compiles into byte-code and thus it can leverage the Java programming language. Its syntax, however, makes it a powerful alternative to Java code in certain scenarios. One of those scenarios is XML processing. Scala lets you navigate and process parsed XML in several ways. It also has first class support for XML built right in, so you don't need to create strings of XML or programmatically build DOM trees. In this article, you will see these aspects of Scala in action and see how Scala can make working with XML a joy to do. Scala and XML

The busy Java developer's guide to Scala: Implementation inheritance

Scala gives you just as much support for implementation inheritance as the Java™ language does — but Scala's inheritance yields a few surprises. Polymorphism done the Scala way, blends functional and object-oriented language styles while still mapping perfectly to the Java platform's inheritance model. The busy Java developer's guide to Scala: Implementation inheritance

The busy Java developer's guide to Scala: Of traits and behaviors

Scala doesn't just bring functional concepts to the JVM, it offers us a modern perspective on object-oriented language design. Scala exploits traits to make objects simpler and easier to build. Traits are both similar to and different from the traditional polarities offered by Java™ interfaces and C++ multiple inheritance." The busy Java developer's guide to Scala: Of traits and behaviors

The busy Java developer's guide to Scala: Don't get thrown for a loop!

Scala's approach to control constructs like if, while, and for - may look like good old Java constructs. However Scala imbues them with some wildly different characteristics. Rather than let you risk the frustration of discovering the differences after you've made a bunch of mistakes (and written buggy code as a result), this month's article is a primer on what to expect when using control structures in Scala. The busy Java developer's guide to Scala: Don't get thrown for a loop!

The busy Java developer's guide to Scala: Class action

Scala's functional programming features are compelling, but they're not the only reason Java developers should be interested in the language. In fact, Scala blends functional concepts and object orientation. In order to let the Java-cum-Scala programmer feel more at home, it makes sense to look at Scala's object features and see how they map over to Java linguistically. The busy Java developer's guide to Scala: Class action

The busy Java developer's guide to Scala: Packages and access modifiers

Scala takes a slightly different approach in respect to packaging, treating it as a combination of the Java language's declaration approach and C#'s scoped approach. With that in mind, a Java developer can do the traditional Java approach and put a package declaration at the top of a .scala file just as normal Java classes do; the package declaration applies across the entire file scope just as it does in Java code. Alternatively, a Scala developer can use Scala's package 'scoping' approach in which curly braces delimit the scope of the package statement. The busy Java developer's guide to Scala: Packages and access modifiers