Anti-Patterns in software development improvement that you ought to avoid

Anti-Patterns
Anti-Patterns

Context

Software improvement is a chaotic activity. So, making use of plan patterns accurately will assist you to pace up the improvement technique by using offering well-proven plan paradigms. Basically, layout patterns furnish reusable options for frequent problems/issues. Besides that, if you use format patterns in your solutions, your supply codes will come to be greater flexible, reusable and maintainable.

Anti-patterns are on the contrary facet of the diagram sample and undesirable. There is any other time period for Anti-pattern that human beings generally use referred to as Design Smell.

What are they?

Note: The list below might be not exhaustive. They are just from my point of view. Feel free to add more based on your experience 🙂

Silver Bullet (Golden hammer)

Photo by Will Porada on Unsplash

Golden Hammer is an anti-pattern that you effortlessly to locate a pattern no longer solely in software program improvement however additionally in each issue of life.
Some humans have a tendency to have their answer equipped earlier than appreciation the hassle like a health practitioner prescribing whilst the affected person nevertheless
telling about the signs and symptoms or like a developer attempting to use modern-day UI/UX frameworks to construct a easy remarks shape with four textual content fields.

In software program development, every graph pattern, every framework or even every programming language is appropriate to the regular problem. However, some humans obsessively use the equal one for each and every trouble that they have to resolve.

As a result, the Golden hammer leads to…

  • Poorly performing code: the chosen one is no longer an environment friendly answer to the problem.
  • Overly tricky code: in the pattern above, rather of the use of some easy line of HTML codes the developer used a contemporary framework like Angular it leads to tough to preserve and even hit immediately to performance.
  • Redundant code: the chosen one now not solely provides no advantage however additionally brings so many vain codes.

How to keep away from this anti-pattern?

  • If you working in a group (especially a leader), you need to analyze to pay attention to other human beings first — don’t be narrow-minded.
  • Always have at least two options for one trouble and benchmark them. List down all PROS and CONS of every answer then pick out the higher one.

God Class

Photo by Rick Mason on Unsplash

A common God class will manipulate many different classes, take many duties as nicely as loads of dependencies. This anti-pattern at once violates the “Single Responsibility” principle.

God lessons are tough to unit test, debug and document. By the time, they will develop up collectively with your utility and come to be the preservation nightmare even untouchable.

Your utility may want to be properly designed at the establishing and there have been no God training at all. However, the necessities and improvement crew measurement will develop day through day. As a result, single clearly-defined instructions will flip into God training at some point.

Here is a sample of God Class:

public class GodClassEmployee
{
	public void GetEmployeeDetails(string employeeId){}
	public void CreateNewEmployee(EmployeeModel employeeModel){}
	public void ValidateModel(EmployeeModel employeeModel){}
	public void ExportEmployeeDetailsToCSV(EmployeeModel employeeModel){}
	public void ImportEmployeeDetailsToDatabase(EmployeeModel employeeModel){}
}

public class EmployeeModel
{
	public string EmployeedId
	{
		get;
		set;
	}
	
	public string EmployeeName
	{
		get;
		set;
	}
	
	public string EmployeeGrade
	{
		get;
		set;
	}
	
	public string EmployeedAddress
	{
		get;
		set;
	}
}

In order to refactor the God class above, we need to divide functionalities into distinct training and interfaces as below:

Import/Export function and Interface:

public interface IImportExport
{
	void ExportEmployeeDetailsToCSV(EmployeeModel employeeModel){}
	void ImportEmployeeDetailsToDatabase(EmployeeModel employeeModel){} 
}

public class ImportExport: IImportExport
{

}

Database Integration

public interface IEmployeeDbOperations
{
	void GetEmployeeDetails(string employeeId){}
	void CreateNewEmployee(EmployeeModel employeeModel){}
}

public class EmployeeDbOperations : IEmployeeDbOperations
{

}

Validation

public interface IEmployeeValidation
{
	public void ValidateModel(EmployeeModel employeeModel){}
}

public class EmployeeValidation : IEmployeeValidation
{

}

How to keep away from this anti-pattern?

  • The improvement crew ought to comply with the “Single Responsibility” and “Interface Segregation” principle.
  • Do code evaluate and observe technical money owed frequently.
  • Classes ought to be properly documented.

Big ball of mud

Photo by Gabriel Sanchez on Unsplash

“Weeks of coding will save you hours of planning.” — Unknow

Big ball of mud is a very frequent anti-pattern that occurs when your solution/application lacks a perceivable, flexible, appropriate architecture. If your utility has the following signs then may want to be viewed as “Big ball of mud”.

  • Haphazardly and sloppy shape barring coding comments.
  • Containing many God instructions with extra than 6000 traces of code.
  • Static variables/functions everywhere.
  • Methods being overloaded countless times.
  • Don’t have the coding convention.
  • Duplicated codes everywhere.

This anti-pattern is very dangerous, because, we don’t recognise that our software turning into “Big ball of mud” till we can’t refactor it anymore and have to determine to rewrite. The purpose why we can’t recognise previously would possibly come from unique motives like necessities changes, the closing date is near, adopting new developers, or even we’re too assured with preliminary format architecture….

How to keep away from this anti-pattern?

In general, we not often can observe the problem when it’s occurring, so each motion must be utilized at the establishing of the project. In case we can become aware of the problem then selections to mitigate are very confined and costly.

  • We have to have a discovery section to diagram the to-be machine and select the most fabulous diagram to practice earlier than the improvement phase. (In some projects, to store the price we typically by-pass this phase).
  • Do code evaluation often in order to observe problems as quickly as possible.
  • At some point, if your structure can’t capture up necessities then you have to take motion intermediately, do not wait till too late.

Error hiding and Exception swallowing

Effective error and exception managing in each software are very essential in each application. They assist to supply a fine journey to the user, as properly as aid developer can without problems debug the trouble and fix, when sudden screw ups occur.

Wait… we’re now not speaking about plan sample or satisfactory exercise here!

In computer programming, error hiding (or error swallowing) is the practice of catching an error or exception, and then continuing without logging, processing or reporting the error to other parts of the software. Handling errors in this manner is considered bad practice and an anti-pattern in computer programming. In languages with exception handling support, this practice is called exception swallowing. — Wikipedia.

With mistakes are swallowed, the developer will no longer have any notion about the root purpose of the problem. As a result, it’s very difficult to parent out what is going incorrect or how to get to the bottom of it.

Here are some Exception Swallowing samples:

  • Re-throwing an Exception: We can re-throw an exception from the “catch” block to ignore on to the caller and let the caller deal with it the way they choose simply to make positive don’t re-throw an exception the usage of exception parameter. Please have a seem to be at the pattern as below:
static void Main(string[] args)
{
	try
	{
		FunctionA();
	}
	catch(Exception ex)
	{
		Console.WriteLine(ex.StackTrace);
	}
}
	
static void FunctionA()
{
	try
	{
		FunctionB();
	}
	catch(Exception ex)
	{
		throw;
	}
}

static void FunctionB()
{
	string str = null;
	try
	{
		Console.WriteLine(str[0]);
	}
	catch(Exception ex)
	{
		throw;
	}
}

As you can without difficulty locate out there is an exception in “FunctionB” and the “catch” block in “FunctionB” simply sincerely throws that exception the usage of “throw” keyword. By that way, the catched exception from “FunctionB” will be dealt with in “FunctionA” — we referred to as it “re-throwing”. In this case, the stack hint of the exception will supply you the full element of the place exactly this exception occurred.

So, what will manifest if you re-throw an exception the use of exception parameter? The reply is that it will no longer keep the unique exception and creates a new exception like the pattern below:

static void Main(string[] args)
{
	try
	{
		FunctionA();
	}
	catch(Exception ex)
	{
		Console.WriteLine(ex.StackTrace);
	}
}
	
static void FunctionA()
{
	try
	{
		FunctionB();
	}
	catch(Exception ex)
	{
		throw ex;
	}
}

static void FunctionB()
{
	string str = null;
	try
	{
		Console.WriteLine(str[0]);
	}
	catch(Exception ex)
	{
		throw;
	}
}

As you can see, exception caught in the Main() technique will show stack hint from FunctionA and Main method. It will now not show Method1 in stack hint as we re-throw exception in Function the usage of throw ex. So, in no way throw an exception using throw .

  • Catching non-specific kind exceptions: We must capture solely the exception sorts you count on to occur due to the fact we disguise bugs in your code otherwise.

Don’t do this

static void FunctionA(string path)
{
	try
	{
		var f = File.Open(path, FileMode.Open);
		// your code logic here
	}
	catch(Exception ex)
	{
		Console.Write("Could not open file");
	}
}

Should do this

static void FunctionA(string path)
{
	try
	{
		var f = File.Open(path, FileMode.Open);
		// your code logic here
	}
	catch(IOException ex)
	{
		Console.Write("File not found");
	}
	catch(UnauthorizedAccessException ex)
	{
		Console.Write("Insufficient permission");
	}
}
  • Baseball Exception Handling: You shouldn’t use exceptions as a replacement for everyday glide manage constructs like if-else statements and for-each loops.

Don’t do this:

static void FindUserName()
{
	try
	{
	    foreach(var user in users)
	    {
		//We found it
		throw new UserFoundException(user);
	    }
	}
	catch(UserFoundException found)
	{
		Console.Write("This is your user name" + found.Name);
	}
}

Should do this:

static void FindUserName()
{
	foreach(var user in users)
	{
		if(user.Name == username)
		{
			//We found it
			throw new UserFoundException(user);
		}
	}
	
	Console.Write("This is your user name" + found.Name);
}

Copy-and-paste programming

image source: Pinterest

Copy-and-paste programming, sometimes referred to as just pasting, is the production of highly repetitive computer programming code, as produced by copy and paste operations. It is primarily a pejorative term; those who use the term are often implying a lack of programming competence. It may also be the result of technology limitations (e.g., an insufficiently expressive development environment) as subroutines or libraries would normally be used instead. — Wikipedia.

We can without difficulty discover an instance of this anti-pattern when do code reviewing for a junior developer or an intern who doesn’t have too lots journey and challenging to construct and supply a function/task from scratch. They have a tendency to search and observe the code that they can discover from the web like Stackoverflow or Github or even from co-workers besides wholly checking out and have an impact on analysis.

In the worst case, this anti-pattern can create is an contamination of your supply code with bugs from the supply material. It acts like a virus and you will have to repair the trojan horse and alternate the code in all places the code was once copied.

Beside junior builders and interns who without problems come to be the sufferer of this anti-pattern, negative appreciation of aspects frequent in laptop languages, such as loop structures, features and subroutines may additionally lead to this anti-pattern.

How to keep away from this anti-pattern?

  • Like different anti-patterns, the fantastic way to keep away from this anti-pattern is that doing code evaluation regularly and carefully.
  • The code which located from backyard your application/solution must be examined and analysed have an impact on region carefully. After that, it have to be reviewed and authorised by using senior participants of your team.
  • When you see a code block acting a couple of times, you need to do refactoring to summary every look into a single feature or method. By that way, if the malicious program is discovered you solely want to restore at one place.

Conclusions

Making errors leads to improvement, so don’t panic if you can locate one or greater anti-patterns in your modern application/solution. Let’s acquire the crew and attempt to enhance one through one.

Hopefully, you don’t want to rewrite complete software 🙂

Photo by Wil Stewart on Unsplash
32 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

three × four =

You May Also Like