DRY code vs. WET code

Published May 30, 2017Last updated Nov 26, 2017
DRY code vs. WET code

Everyone knows that dry stuff is lighter and easier to maintain, manipulate, and store. You wouldn’t want to keep wet cloths in your suitcase — it would create unpleasant smell and increase the weight of your bag. In short, it’d be really bad.

When it comes to programming, DRY and WET practices can be taken the same way — you’d want to avoid the WET ones. With that said, DRY and WET are actually acronyms: Don't Repeat Yourself and Write Everything Twice. Though most things have both positive and negative sides, sometimes, something is so good that you almost forget about the disadvantages.

Let’s go back to programming — programming is the process of solving problems locally and creatively. It is often done through modelling ideas into code. My comparison of DRY and WET will be based on two of the most important things in computing:
TIME: System.currentTimeMillis()
SPACE: byte
I’m sure you will agree that these things are very necessary.

Your computer has a lot to do, so why write code that will cause it to waste more time on compiling? Your machine has so many threads to execute too. Okay, even if you don't give a sh*t about the computer, this should bug you! Maybe you’d rather spend your time on a date with that nice person you met at the tech conference, or maybe you are planning on delivering the software on time to a client. Time is money — faster software would come in handy. Windows Vista is cool but I hate watching it start up or shut down. I usually start my Vista up before I head to the next street to get a Suya (a tasty hot roasted beef in Nigeria), so that when I'm back, I will be able to use my pc without having to wait for it to boot. Mind you, I don't use a password on Vista because if I did, I may have to go and get another Suya. I also go and take a shower when it’s shutting down. As you can see, time is key in everything. You don't want to define a function that performs the same logic every time you need it before calling it. You can actually define such a function once and call them elsewhere with a different input for such function or logic to work with.

Memory is also key.

Exhausting memory or using memory unnecessarily is a sure way to get your program into the trash. Making your code WET can help you get there. Remember the early days of computers when their storage hadn’t even reached a kilobyte? I bet you wouldn’t have wanted to write programs back then!.

Now, let's try and fry some Akara (bean cake), some WET code, and some DRY code and see which one is more preferable in the long run. The prototyped functions below are meant to perform some operations to see if an Uber driver is around and check if the time is afternoon or night:

function callUber(){
  uberDay();
    uberNight;
}

function uberDay(){
  if(driverIsAround() && (time > 5am && time< 10pm)){
    	print('driver will be around in 3 mins');
    }else{
    	print('sorry there no available driver around you');
    }
}

function uberMidnight(){
  if(driverIsAround() && (time > 12am && time < 5am)){
    	print('driver will be around in 3 mins but u don not want to go out now');
    }else{
    	print('sorry there no available driver around you');
    }
}

The above looks too wet and can be made dry in many ways. Let's consider the below, which will perform same thing as the above

function callUber(){
  uberTime();
}

function uberTime(){
  if(driverIsAround()){
    	if(isMidNight()){
        	print('driver will be around in 3 mins);
       	}else{
        	print('u don not want to go out now though driver is around'));
        }
    }else{
    	print('sorry there no available driver around you');
    }
}

//such that you can have a method isMidNight() that check what time of the day.

Some development tools that can help keep your code DRY

IntlliJ IDEA: I have been using Netbeans IDE for almost all of my code, but when I started using IntlliJ IDEA, I discovered some cool new features I never thought an IDE would have. A very beautiful function is that the smart IDE checks for code logic or code block duplicates in a project and highlights them for you. So, all you have to do is correct them. Android studio also does the same thing. I believe Webstorm, among other Jetbrain products meant for coding, will definitely have this great feature as well.

Some WET code cases you can avoid

Network requests and treating network responses.

WET code used to arise when you make connection requests and treat response of a request. For example, you have a request that always return 200 or 304 for HTTP OK response status and 404,401,500 among others, due to some sort of error. You, however, need to do this check on every request you are making for login, register, readpost, makepost, deletepost, editpost among other hundreds of APIs. That's the problem: Hundreds! You shouldn’t have to write 15 - 50 lines to handle your error every other time. You can write a code that applies itself as an interceptor to your network request and perform these operations on it.
I love this way of doing it in Angular/NodeJS

function authInterceptor(API, auth) {
        return {
            // automatically attach Authorization header
            request: function (config) {
                var token = auth.getToken();
                if (config.url.indexOf(API) === 0 && token) {
                    // using this to keep sending Authorisation token back to the server on every request
                    config.headers.Authorization = 'Bearer ' + token;
                    config.headers.token =token;
                }
                return config;
            },
            
            // If a token was sent back, save it
            response: function (res) {
                
                if(res.statusCode == 200){
                    // TODO some success logic
                    
                }else if (res.statusCode == 401){
                    // TODO some unauthorize access logic
                    
                }else if(res.statusCode == 404){
                    // TODO some resource not found access logic
                    
                }else if(res.statusCode == 500){
                    // TODO some server error
                }
                return res;
            },
        }
    }

You can do this once in your service while you make the service a dependency in your other Angular code where you need to repeat these processes. This approach is also applicable to RESTful Web Service API whose response follow a consistent approach like this:

{
  "status": 1,
  "message": {}
}

for a successful API call and

{
  "status": 0,
  "error": {}
}

for a failed API call.

You can handle your status and error in one process that applies to every API call while you only need to deal with "message" returned on success.

Connecting to database

Consider JDBC connection in Java. You don't want to keep repeating the connection code every other time (though you may not want to keep the connection open while you exit your app). You can always do a final check in the app life cycle when you are about to kill your app. You can also write an abstract class or interface as the case applies, which you will need to implement a function/method that performs just your own logic, while others are performed for opening connections and closing them in the abstraction logics.

Advantages of keeping a DRY code (The Good)

  • Maintainability — Since you already defined logic that would do more stuff, when you need to update your code later, it would be easier to change the stuff in one logic, which then applies to every other applicable point
  • Readability — You can follow the codes easily
  • Reusability — You won't need to defines stuff more than once instead you will reuse the already written logic that perform the same operations
  • Cost — DRY coding approach saves you time and space
  • Testing — Unit testing is easier with DRY code. You won't need to define configuration and test function for every function but only the defined functions. So if you have a WET code, you will perform more unit tests

Disadvantage (The bad)

  • Over-dried code may not be easier to read because you will have to many logical callings to follow
  • You may need to think a lot when you’re implementing DRY code, especially if you’re not that familiar with them

The Ugly

Personally, things look ugly to me when a code is too WET. It often makes me feel like the code is not clean and tidy enough.

More things like implementing OOP - Inheritance, polymorphism are good practices for avoiding WET code.

Please feel free to comment on more ways of keeping your code DRY.

Discover and read more posts from Joshua Aroke
get started