Be declarative wherever possible

Imperative programming focuses on describing how a program operates. Take an example of the below function “ isPresent “.

First example: Imperative way, Look implementation of isPresent function.

Of course, it searches a number (search term) in the numbers array and replies with true or false.

If you observe carefully, it focuses on how the number is searched.

It iterates each number one by one in an array of numbers and checks if criteria are fulfilled (HOW part: for/if). Eventually, it tells you if the number is present/not in the array.

Declarative programming, on the other hand, expresses the logic of a computation without describing its control flow.

Let’s look at the declarative way of searching a number in an array.

Declarative way: Any function from LINQ.

In the above code, the method Any (present on array data type), is an extension method provided by LINQ.

It determines whether any element of a sequence contains a given number. It does not tell you how it is searched. That part is hidden behind API: Any.

The benefit of a declarative approach over the imperative approach is improved readability of code.

Another example:

Second example: Imperative way. See containsAllMen function: focuses on describing how a program operates (Control flows are involved: iterate and if)

This function “ containsAllMen “ tells you how searching is implemented and control flow like if clause determine the condition.

Now see the declarative way, it is using lodash’s every to determine the condition.

The declarative way: Using every function from lodash.

This technique is language agnostic.

You search libraries that do such work for you instead of implementing it by yourself.

Start slowly to finish fast

“In programming, the hard part isn’t solving problems, but deciding what problems to solve.” – Paul Graham

I am fortunate enough to work with new, genius, competitive developers who have fresh perspectives. They often talk about faster algorithms, data structures, new-generation technologies, and buzzwords in the software industries. They are eager, motivated and wanted to change the world!

However, I did not hear from them about problem-solving using object-oriented analysis and design.

Some people try to solve the problem by directly jumping into programming solution without doing an analysis. They believe in trial and error methods. It’s like solving problems without knowing what problems to solve.

The well-proven OOAD techniques are there for decades, It’s a very beneficial technique for problem-solving. They will help you to know what problems to solve.

We should focus on what problems to solve rather than just writing the code.

IMO, we should start slowly to finish fast. What I mean here is, we have a problem at hand, divide it into three parts: Analysis, Design, and Programming.

These three are related terms.

The object-oriented analysis is meant for understanding the customer problem. Write use cases to capture what is needed and what is not. You can write lightweight use cases. Thus, you’ll focus on what is needed than trial and errors.

Benefits of writing use cases!

The next step would be the object-oriented design which emphasizes on designing the conceptual models i.e. classes to achieve the various use cases.

This classes will have attributes and behaviors. They interact with each other to solve the problem.

Try using outside in approach, class diagrams, sequence diagrams. You could use the whiteboard to evolve your conceptual design that tries to solve the customer problem.

Object-oriented thinking, the big picture!

Then comes the programming phase. Now you know “what part” of the problem and conceptual models, you can focus on how part i.e. coding.

The good analysis and design would help you to understand problems to solve, prepare good conceptual models, that intern leads you to good programming solution for the problem at hand.

Remember, don’t directly start coding without understanding the problem to solve.

Instead, use object-oriented analysis and design.

Start slowly to finish fast.

Effective stand-ups

Stand-up is considered to be the most important event in Scrum. Although there are numerous guidelines on how to run effective stand-ups, here are some of the tips based on my experience.

Why Stand-ups?

  1. Stand-up’s offer a means to share and build a knowledge base in the team. It’s a 2-way channel, as in, “Every problem is TEAM’s problem” and “Every piece of information is TEAM’s property”. Over a period of time, it helps the team develop good capability to collectively solve problems, thereby building “Self-Organizing teams”.
  2. They are necessary for promoting transparency which is extremely important for retrospection and improvement.
  3. As a side note, not everybody in the team is same. Some people are introverts. Everybody should get a chance to express themselves and get involved. Working in isolation has adverse effects in software development.

Here are some of the tips to improve the stand-ups

  1. Come prepared:- Most basic, and also the most overlooked thing. Come prepared about what you are going to share in stand-up.
  2. Be attentive:- Once you finish talking, do not get distracted. Maintain focus and listen carefully to other team members. This shows that you respect others and are eager to get involved. Plus from a career perspective, solving other’s problems can take you a long way ahead.
  3. Start it daily at a fixed time:- Some amount of discipline is necessary in software development. Although, sometimes it is ok if someone misses a stand-up due to unavoidable reasons, after all we all are humans 🙂
  4. Have quality discussions:- Although Scrum says a stand-up should not exceed 15 mins, it is better to focus on quality than quantity. It is ok to go into details of things, it helps everybody learn from each other. If someone faces a similar issue in future, they know where to look for and whom to talk to.
  5. Maintain a sidebar:- If the discussions go for a long time, take it offline, and put them in a sidebar.
  6. Maintain a board:- Although there are many ways used by teams to look at the work of current sprint, (such as TFS board, Jira board), IMO nothing beats a simple whiteboard. The main reason for that is you can customize a board as per your needs, add more columns, maintain more important information, stick more stickies for things which you feel are important.
  7. Retrospect on stand-up:- Reflect on the way the stand-up is conducted and run. Is it adding value? What are the pain points? Can we use our scrum board to help the situation improve? In one of the teams, I worked for, failing regression tests were a serious and frequent problem. We decided to put that number on the board in bold and red. We also decided to fix at least 5 tests per sprint. This lifted the transparency and people passing by the board took notice of that. Soon other teams also discussed this in their stand-up and joined in our efforts. We reached the stage where all tests were in green with the collective effort.

Asking “Why?” and seeking the answer for it is the most crucial step in any process. The most junior member should feel comfortable to question the most senior person in the organization. Things don’t work just by telling or imposing them. The one’s involved in the process should understand the “Why?”. This will establish a permanent connection between people and processes.

Object oriented thinking, the big picture

I see my recently graduated friends solves consumer problem by the procedural way (writing everything in a single class or a method) using object-oriented programming language.

In this post, I am sharing what and how I think while solving the consumer problem, The object-oriented thinking!

IMO, as an object-oriented designer, I divide the big problem into smaller ones. I provide the solution for small problems (concerns) using objects. Eventually, these objects communicate with each other by sending messages to solve the consumer’s big problem.

Let me explain it with the help of the use case. (We will consider the server-side solution)

Problem statement:

As the new user of the system, I want to register a user account.

We would consider only two fields on the user registration page, Name, and Email and sign up button.

Use case:

User can create his/her account

  • As a user, I navigate to the registration page.
  • Enter name and email.
  • Choose to register.
  • The user account is created.
  • Email is sent to the recipient.

The user cannot create an account when a name is not provided.

The user cannot create an account when email is not provided.

Solution:

As a developer, I need to provide the solution for these use cases. (I know there could be many alternate cases, however, let’s keep it simple.)

Clearly, there are different concerns that need to be addressed.

IMO, we need a class:

  • To validate the user inputs.
  • To create a record in a database.
  • To generate email content.
  • To send user registration email.

Thus, I would divide the concerns into

  • UserValidator class that validates user inputs and gives an error for validation rules like the name is required, email is required and so on.
  • UserRepository class that takes user entity and insert records into the database.
  • EmailTemplate class that generates the email content.
  • EmailSender class that takes email content and sends the email to the recipients.

UserController class that does the following stuff and try to solve the big problem by sending messages to the object of the above classes.

  • Verify the user inputs.
  • Create a user in the database.
  • Get registration email content.
  • Send registration email.

Note: To convey the intent, I kept this design as simple as possible. We could give more clean solutions like outsourcing the responsibilities of the controller (Keep controllers as thin as possible) to model classes and so on. Please feel free to share your feedback with me.

You can observe, The proper object-oriented design would divide the big problem into the smaller ones across classes. Solve small problems in order to solve the bigger one.

https://blog.beingcraftsman.com/datta/

Workplace happiness

Do you feel unhappy at work?

Do you think about Monday on a Sunday (Called Smonday)?

Do you find reasons to take a leave off work?

Do you think of leaving your current job and following your passion?

If the answer these questions is a “NO”, then that’s great. You are doing an awesome job in life.

However, statistics and surveys done worldwide show some interesting perspectives about being happy at work. Let’s explore.

In one of the teams I worked with in the past, we used to share “How happy are you today?” at the end of stand-up everyday. It was a simple practice to share how you are feeling or what your mood was on that particular day. It sort of provided a heads-up to other team members about what to expect and adjust their empathy levels accordingly. I realized that “Happiness” is quite a serious topic, when I explored it more.

Happy employees are more engaged at work. Objectively speaking, studies (for ex, this one), show that

  1. Only 13% employees worldwide are happy.
  2. 63% are not engaged. You can say they are working just for the sort of making a living. They have no attachment with their surrounding.
  3. And 24% are actively disengaged. 24% ?? Almost a quarter of world’s working population is unhappy, grumpy and toxic at workplace. That’s a very high number.

The financial losses due to unhappy and disengaged employees run into trillions of dollars worldwide. Such employees are active in further spoiling the culture.

Happiness and culture are very closely related. Happy employees are more productive, promote the culture and encourage more people to join the company. They are simply great at everything they do. That’s the reason many companies these days are investing in this area and have have dedicated and trained people to improve employee happiness and productivity within the company. Pluralsight, example, has a Chief Happiness officer which is amazing.

There are a number of recommendations and studies on how this problem can be approached. Management 3.0 speaks about this and so does this report.

Keeping employees happy is a challenge. Having worked with many teams in the past, I have been both happy and unhappy at work. Below are the top 3 things that affect people happiness, which I have experienced.

  1. Respect:- This one tops my list, at least. Teams these days are built with people from diverse culture and backgrounds. Some may be introverts, some may be extroverts. The most common reason why people are unhappy at work is because they do not feel respected. There are a number of acts that can make people feel bad. Mocking someone, rejecting ideas in a rude way, raising voice and doing arguments are some of the behavioral traits. Give timely and immediate feedback to any individual who shows exhibits certain behavior. Do not let it grow.
  2. Bad bosses:- Peter’s principle is largely prevalent in our industry which is wrong and should be avoided. Do not promote technical people into managerial positions, just because they do not have room to rise any further in the organization. Managing people is a niche skill and needs specialized training and education. It’s a well known fact, that most people do not leave companies, they leave their bosses.
  3. Right people for right job:- People feel happy when they accomplish something. They feel proud when they are recognized for their accomplishment. This motivates them further. Recognize the potential and setup people to succeed, rather than to fail. If the employee does not have competence to undertake a difficult task, be explicit and let him/her know about it. Set goals and expectations as per potential and competence. Competence is a temporary thing and it can scale to great levels if the person is motivated to work hard and put in efforts.

There is usually a built-up process involved, over a period of time. Nobody decides to leave a company just in a day. Which means there is always time and opportunities available to make corrections. Look around, talk to people, gather feedback and safeguard the culture, because at the end of the day, happy employees can create great companies.

Creating reliable “Objects”

Let’s start of with a piece of code.

We have a Main( ) method, which creates an object of a Circle class, sets the radius and then calculates the area of the circle. Let’s have a look at the circle class. It has a simple implementation to calculate the area of circle.

The above code looks simple and it works. Are there any flaws in it? Let’s examine.

What if the consumer of the Circle class, does not set the radius correctly? For example, like this,

circle.Radius = Convert.ToInt32("abc");

The call to CalculateArea( ) would fail, because the input cannot be parsed into an integer. By design, the Circle class  is allowing other classes to control the Radius property. The consuming classes, may set unacceptable values for the Radius property. This leads to unpredictable results from the CalculateArea( ) method. We can do a validation check for the Radius property either in it’s setter or the CalculateArea( ) method. That would work. Perhaps that is a natural approach we adopt most of the time.

But let us for a moment take a step back and think more in terms of object orientation. Imagine someone asks you to draw a circle on a piece of paper. Your obvious question would be, “Sure, how big or small do you want it?”. In other words, in order to “construct” a circle, you would need the information about it’s radius.

One more important aspect in this example, is that a Circle is immutable. Once we create circle with a certain radius, we cannot change it. Making the setter for Radius property as public allows the consuming classes to alter it, even after it has been created (Hmm, not good.)

It is therefore always a good idea to create objects in a robust way, when they are being constructed. The radius property is integral to the Circle class and it is the responsibility of Circle class to manage it. The clients just need to provide the details while creating the objects. If the client code provides incorrect information while constructing the object, the class can choose not to go further with its creation, thereby protecting its integrity.

Below would be the correct implementation of Circle class.
The above example was a simple one. We just had one property to deal with. But in reality, we need to deal with classes which have a lot of properties and really complex methods. Ensuring correct values in all properties throughout the lifetime of an object can be a very tedious task. This leads to many potential bugs. It is impossible to predict the ways in which the consumers of the classes would consume them. This leads to responsibilities scattered all over the place and classes that are strongly dependent on each other.

In addition, once we make a property as public, it is very difficult to make it private again, because by the time you realize that you need to do that, there may be a number of places, it has already been consumed and used in different ways.

As a thumb rule, try to restrict the access to all the properties in the class when you write it for the first time. This will allows you to encapsulate the class properties and the code to manage them inside the class itself. If you need to make any property as protected, internal or public, think and try to find for a strong need and justification for doing so.

 

Do not catch “Generic exceptions types”

(Below scenario may be hypothetical, but for explanation purpose, let’s consider it happens…….)

Imagine you are using a service for achieving some task, for example, let’s say, you are buying something on an online shopping portal.

It so happens that while surfing for products, the site crashes. You contact the support and they tell you it was a “SYSTEM ERROR” and they will get it fixed. Such things happens and it’s ok for you. You move on.

After a few days, you are trying to purchase something on this website and while checking out, the site crashes in the 3rd party payment gateway. This time you are a little annoyed and you contact the support again and tell them your story. The support tells you it was a “SYSTEM ERROR” and they will get it fixed. You move on, since you cannot do anything about it besides trying again.

Time passes by and after a few days you successfully place an order with this site. You are excited about your product, it’s a new gift for your spouse. But this time the product goes to a different warehouse in a different city and the product does not reach you. You again contact the customer care, and they tell you again that it was a “SYSTEM ERROR” and they will get it fixed. This time you get furious. How could it be a “SYSTEM ERROR” every time something goes wrong? You want more details about the problem, you want to hear more about what went wrong. After all, you have invested your time, money and effort in this activity.

This is exactly how the consumer of our library would feel if we return them a generic exception type, every time something goes wrong.

The consumer of the code code expects more details to either fix the problem or get the problem fixed. Standard libraries such as .NET, precisely describe about each exception that can be expected from the calling code. If your API has business logic and you want to enforce certain things (for example validation), you can return your own exception types (by deriving from base) and communicate the same to the consumer of the API. In this way the consumer knows what to expect when and take necessary actions.

Exceptions should be handled on case-to-case basis. Catching generic exceptions is a code smell and has to be strictly avoided. They indicate negligence to detail. Microsoft does not recommend suppressing this rule. More details can be found on MSDN here.

Encapsulation


Encapsulation is the process of putting data and code (that operates on data) together in a single unit, which, acts as a protective wrapper for data and code. Access to the data is provided via controlled access (public interface).

Consider an example of a simple wristwatch.

Abstraction means to provide the simplest view of a complex concept (showing only the necessary part). So, in this case, it displays only time.

Encapsulation means not only provide the simplest view of complex concept (Abstraction!) but also hide and protect internal implementation. The end user cannot see how time is being calculated; what gives energy to the wristwatch; how the internal circuits are structured and so on…

The glass and plastic body forms a protective wrapper (Encapsulation) which hides the internal implementation details (hiding the complexity) and shows the current time (…only relevant part, Abstraction!).

Encapsulation gives access to modify the data via the controlled public interface. In this case, it’s a push button which is used to change/set the time.

From this example, it is clear that the two concepts are related. Without proper encapsulation, there would be no abstraction. Encapsulation not only helps a code achieve abstraction (shows only relevant functionality) but goes one step further and hides everything else, which is irrelevant to the user.

In essence, Encapsulation picks up where abstraction leaves off. In code, you will either have both abstraction and encapsulation, or you will have neither.

https://blog.beingcraftsman.com/datta/

Abstraction

Abstraction is the ability to work with the concept/idea while safely ignoring some of its details. Rather, handle different details at different levels.

Take an example of a simple fan regulator. As a consumer of it, I can focus only on regulating the speed. Here, changing the speed via the interface (knob) is the concept while I will ignore other details like an internal electronic circuit that consists of a diode, capacitor, resistors, DIAC, TRIAC and so on..

Internal of the fan regulator.

Thus, Abstraction is the process of showing only the relevant details with which consumer can safely work with.


Real-life analogy

When we consider a laptop as aggregate, it is an abstraction of its various parts, like a keypad, touchpad, screen, motherboard, hard-disk, processor, etc.

Similarly, A keypad as a whole, in turn, is an abstraction of a particular arrangement of keys and internal wirings.

This way, abstraction allows you to take a simpler view of a complex concept.


Similarly, in software development, abstraction should manage the complexity of the software design at a different level. A good abstraction should lead to a good (less complex) software design.

In languages like C++, Java, C#, we can achieve abstractions via abstract class and interface.

Good programmers create abstractions at the method level, class level, interface level, namespace level, and assembly level —in other words, motherboard level, keypad level, and laptop level—and that supports faster and safer programming.

As programmers, we need to provide the right level of abstraction in accordance with the need of the end consumer.

Method cohesion

Image credit: https://www.slideshare.net/agileee/lightening-talk-software-craftsmanship

The Method exhibits high cohesion when a method performs one and only one operation and do what their names say they do.

If they do anything else, they are less cohesive and poorly named.

Examples of highly cohesive methods:

  • GetProductName()
  • PrintBarcode()
  • ToLower()
  • CalculateAge()
  • CreateUser().