Algorithms Archives - Simple Programmer https://simpleprogrammer.com/category/algorithms/ Wed, 11 Mar 2026 01:50:38 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 5 Skills Students Need to Get Their First Programming Job in 2021 https://simpleprogrammer.com/programming-student-skills-2021/ https://simpleprogrammer.com/programming-student-skills-2021/#respond Mon, 29 Mar 2021 14:00:49 +0000 https://simpleprogrammer.com/?p=38452 A detailed rundown of the skills needed to pursue a programming career in 2021, as well as tips for listing these skills on a resume.

The post 5 Skills Students Need to Get Their First Programming Job in 2021 appeared first on Simple Programmer.

]]>

programming jobs skills 2021What skills do you need to land a programming job in 2021? Well, this is a tricky question to answer. In today’s world, programmers need more than just IT skills to survive in the job market.

As a college student who new to the world of programming and has dreams of becoming a successful programmer, you will need a wide range of skills to help you perform optimally and carry out your job responsibilities. The best programmers often combine their software engineering skills with other soft skills, which helps them stay at the top of their game.

According to research carried out by Google, successful tech experts and developers have soft skills prevailing in their knowledge kit. This simply proves that modern companies are now looking for programmers who can offer more than just coding skills or STEM expertise. So, if you’re ready to become a gem in the software programming job market, read on about some of the most profitable skills to learn in 2021:

Develop communication skills

There is a popular stereotype of programmers who sit solo in a corner, working on their computers without saying a word to anyone. While this may be true in some cases, it doesn’t take away the fact that you need excellent communication skills to work on both simple and complex projects.

But how do you communicate with a team on a deep level? Well, to interact with people professionally, a great programmer should be able to have a clear understanding of problems and then propose viable solutions coherently. One way to ensure that you get an accurate perception of problems is by working on your listening skills. Having the ability to listen, you can easily grasp the issue that needs discussion and draw meaningful insights from it.

However, excellent communication skills don’t just end at listening and speaking. They also involve being able to read the room and knowing the appropriate time to suggest any solutions you may have.

To boost this skill, you could practice talking to other students in a clear and coherent manner. That is, your ideas should be easily understandable even by a layman. There’s no need to speak for hours or cram programming jargon in your sentences.

You could practice speaking up by actively participating in group presentations. Don’t be scared to take the front stage every now and then.

If you’re struggling with practicing in your physical classroom, there are tons of online communication courses you could take on Udemy or Coursera. Such courses let you dictate your own pace so you won’t have to worry about interference with college work.

Brush up on your mathematical skills

Let’s admit it: you probably skipped math class once or twice in high school. While this may not be a big deal in your personal life, it may pose a little problem if you’re trying to pursue a career in software programming.

Most niches in programming require a thorough understanding of basic Algebra and Arithmetic since programming is often considered as applied math. For instance, in basic programming, binary math is used to represent numbers in a computer. Similarly, linear Algebra is used for the transformation of matrices.

Even calculus problems pop up every now and then in machine learning, as the former is one of its major pillars. For instance, the concept of calculus is used in algorithms such as Stochastic Gradient Descent (SGD) and Gradient Descent algorithms.

If your mathematical skills are dismal, you may want to consider getting a tutor or visiting the world’s largest tutorial hub – YouTube (you can start by checking out the Simple Programmer YouTube channel!) Focus on Algebra and/or Calculus as these studies are the most relevant ones when it comes to programming.

Work on Problem-solving

programming jobs skills 2021The whole essence of programming is centered around solving both complex and simplistic coding problems. This is the meta-skill that defines your status as a programmer. You should be able to demonstrate computational thinking and break down complex problems into solvable ones.

Generally, code is often written to solve a particular problem. As a programmer, you will be required to identify problems and then come up with viable solutions. If you don’t have a passion for solving problems, you will most likely end up frustrated because, in some cases, you may need to develop multiple solutions for one problem.

To help boost your problem-solving skills, you could try practicing this way: search for a common programming problem (Topcoder is a great crowdsourcing company that offers challenging projects) and then come up with a solid plan to tackle it. You can come up with a strategy by studying the problem and brainstorming common solutions to similar issues. The way expert programmers tackled their problems will give you an insight into possible solutions.

Next, divide the problem into sub-problems (this process is called dynamic programming) and come up with sub-solutions. Once this is done, you can connect the dots and generate a solution for the original problem. For instance, if you’re trying to find the Longest Common Subsequence, you could break down this problem, make a flowchart, and then go on to practice pseudocode.

Improve your writing skills

This may come as a shocker to you (or not), but programmers have to be good writers as well. A professional writer is the one who can coherently discuss technical implementations and complex topics in written discourse. In addition to your IT skills, you’d also need to have a flair for writing in a way that ensures your message is passed across. As a programmer, you’d most likely find yourself doing a lot of technical writing. Hence, you should be able to explain complex concepts and processes in a non-technical way when documenting your work.

You may also find yourself in situations that require you to document or communicate your processes and results to people who may not have the same level of technical knowledge that you do. For instance, you may need to answer programming questions from less technical clients via emails or other communication channels. In such cases, it’s best to have a proper touch for words and be flexible in your expressions, depending on message recipients.

Have a Healthy Dose of Inquisitiveness

No one says you have to be a Curious George who annoys their team members. However, successful programmers with decent IT skills often have a healthy dose of inquisitiveness towards problems and solutions. For example, you should ask questions like: How does this line of code work? Why does action A solve the problem but action B doesn’t?

Even though curiosity kills the cat, it does the exact opposite for any software programmer. Therefore, inquisitiveness will help you learn new concepts faster and stand out from the crowd.

If you’re curious, this trait will fuel your desire to code and help you to dig deep into problems. Subsequently, you’d learn new concepts and solutions that you didn’t even know exist.

A great way to develop curiosity as a programmer is by constantly experimenting with coding projects and problems. These experiments will generate new questions for you to find answers to, and as such, ignite your curiosity.

List These Skills in Your Resume

Now that we’ve outlined the top skills that would land you a programming job in 2021, it’s important to learn how to list them in your CV. Doing this will make your resume stand out and definitely catch the eye of even the most impatient recruiter. But how exactly do you do this? Here’s how:

Add the ‘skills’ section

There are two major options you can choose from if you’re trying to figure out a way to list your skills. You may decide to create a separate skills section and then list out specific skills and qualifications. However, this option is more suitable for people who have had extensive experience in the field, and this brings us to the second option.

Alternatively, you could simply weave your skills into your professional experience section. This is an excellent option for budding programmers as it is the right way of stating that you have little professional experience.

Use examples

When listing your skills, it’s important to pad them with specific examples in order to provide additional context. For example, if you’re listing problem-solving skills, you should ‘seal’ your expertise with examples when you encountered a complicated coding problem and solved it using computational or critical thinking. This way, a recruiter will be assured you do have expertise in the field and can boast of more than just generic soft skills.

How To Improve Your Programming Skills

programming jobs skills 2021If you’re a newbie to the world of programming and have little IT skills, there’s a huge chance you may be feeling under-skilled, especially when you compare yourself to experts in the field. Now that we’ve discussed the soft skills you need to have as a budding programmer and how to list them in your CV, here are some tips that will help you raise your capacities and become a pro in the game:

Read code

This is one of the most valuable hacks for honing and bettering your programming skills. Read code written by other programmers and set a challenge for yourself. When you read other programmers’ code, you get to see how they solved the problem and thus can figure out alternative routes through which you could have solved it.

You could also read articles, newsletters, and programming books such as The Clean Coder or Introduction to Algorithms to learn more about coding and problem-solving.

Write code

What is a better way to learn how to write code than by actually writing it? Working on personal programming projects offers you the opportunity to get first-hand knowledge and experience in the field.

With constant practice, your programming skills will improve.

Learn techniques rather than tools

Here’s one thing you should know about programming and technology in general: tools come and go. The coding tools you use now may become obsolete in the next few years.

As such, you should focus on learning the basic details of programming and getting practical advice instead of becoming overly reliant on tools. This way, you would not find it challenging to adapt to new programming apps and changes.

Network with other programmers

It certainly helps to cooperate and exchange ideas with other experts in your field, especially if you plan to pursue a programming career in the future. You could also try visiting hackathons or coding boot camps during semester breaks to network with other people like you.

At these boot camps, there’s a huge chance that you’d find an expert who can answer any questions you might have about professional coding. However, if you’re too choked with college work to visit a boot camp, you can join online coding communities and connect with other budding programmers to widen your scope of knowledge.

Kick-start Your Programming Career by Learning These Skills

If you’re trying to land a lucrative programmer job in 2021, you’ll need to be armed with the right skills and experience. You’ll need to work on your communication, writing, and problem-solving skills and improve your hard programming abilities by reading and writing code and learning new techniques.

The five skills listed in this article will not only look good on your computer programmer’s resume but will also land you a dream job. Good luck!

The post 5 Skills Students Need to Get Their First Programming Job in 2021 appeared first on Simple Programmer.

]]>
https://simpleprogrammer.com/programming-student-skills-2021/feed/ 0
Using The 75% Algorithm to Change Your Life with Weight Loss https://simpleprogrammer.com/75-algorithm-weight-loss/ https://simpleprogrammer.com/75-algorithm-weight-loss/#respond Fri, 24 Mar 2017 14:00:28 +0000 https://simpleprogrammer.com/?p=22419 Where I’m Coming From In my teens I was heavy, very heavy. I have always been a big guy but this was not an issue of being large-framed or big-boned, even though I am 6’4”. I was fat, I was obese, and I hated being that way. The first 17 years of life didn’t teach...

The post Using The 75% Algorithm to Change Your Life with Weight Loss appeared first on Simple Programmer.

]]>
Where I’m Coming From

In my teens I was heavy, very heavy. I have always been a big guy but this was not an issue of being large-framed or big-boned, even though I am 6’4”. I was fat, I was obese, and I hated being that way.

The first 17 years of life didn’t teach me very good dietary or exercise habits, and the issue was only exacerbated in my early teens, when I discovered my love for computing technology. I spent countless hours sitting on my butt with my face buried in my computer monitor. I learned a lot about computers and programming, but gained a lot of weight on top of already being heavy.

During the worst years of my teens, when I was inactive and habitually eating very poorly, my weight maxed out at 398 pounds. I hated being that heavy but had no compelling reason to change and so I didn’t. I sat at my desk, ate chips, and wrote C code.

It wasn’t until I entered college at the age of 17 that I started caring about my weight and my appearance. Most people would think that the societal and peer pressure of high school might have encouraged me to change, but unfortunately I did not have that influence, as I was homeschooled through high school. And let’s be honest with ourselves, even in public schools there are plenty of excuses to not care about how we look, and how healthy we are.

After entering college, it didn’t take long for me to feel an overwhelming desire to change. I didn’t want to die of a heart attack at 45, I wanted to fit in, I wanted to be able to participate in sports and physical activities, and even more, I wanted to have a fighting chance at dating, and, given that I was already an antisocial nerd, I knew I needed any help I could get.

At first I didn’t have the first clue about what I needed to do to lose weight and get in shape. After my first year of self-loathing and overwhelming desire to change I began to study, and study, and study, and what I found was that there is no magic diet, no wonder pill: nothing but hard work and smart thinking was going to help me. Being a technically minded individual I felt like my best approach was to program myself into a healthier lifestyle.

And so I set out on a path that would change every aspect of my life for the better. It is my hope that the experiences I have been through, the process I created for myself, and the knowledge I have gained will be a help to others who have been in, or who are in, the same situation that I was in.

The Overview

The learning process that I went though has several stages, and unfolded over many years. I want to give you a brief outline of the key stages to making a transformative lifestyle change before I tell you about my journey through them.

Mental Preparation

The first step is mental preparation. You will have to be harsh, and brutally honest with yourself during this stage. As much as honesty can hurt, and as hard as it is to be so grossly unhappy with yourself, it is a necessary part of the process in order to motivate yourself to change.

I went through years, in my teens, of disliking myself and my body, hating that I sat on my butt at my desk all day and all night. When I entered college I was doubly unhappy with myself and my body and all that time of self-loathing was preparing me for a change.

Ultimately, the motivation to change has to come from within. No one will make you change or make you lose weight; you have to have the motivation and mental preparation for yourself. This is exactly the same as solving a hard coding problem, designing a complicated system, or even writing a long boring technical document. The focus and motivation has to come from you.

Habits & skills

As with learning any new discipline, it is more important early on to memorize what you know is correct and act on it, even if you don’t understand yet why it is correct. Park further away from the door. Take the stairs instead of the elevator. Never order a “large” combo meal from the drive-through. Eat more fiber. Drink more water. All of these things are little examples.

When you are learning to code, your text books or instructors tell you, “Never use a GOTO! GOTO statements are bad!” You don’t know why they are bad, but you sure as heck don’t use them. You have to build up good habits, and good decision-making abilities before you can think for yourself. (This is different from willpower,  as I will explain later on).

This was the second stage I went through: training myself to see my own life from the outside in, and practicing good habits and good decision-making, even if I didn’t understand why something was important.

Major activities

Once I had some basic skills mastered and knowledge sets acquired, it was time to start really flexing my willpower and basic decision-making skills. I started out by walking around my block every day, no exceptions. Over time, as it became easier and easier, I forced myself to do more laps, until one day I began to jog the laps— fewer than walking at first, but eventually I built back up to the same number of laps, and more.

Adding activities that will exercise your body, but also provide you with joy is a major part of changing your health for the better. If I had gone to the gym every day and made myself work out on an exercise machine, I’d have been bored out of my mind.

Getting outside gave me exercise, and gave me some joy. You have to have both to succeed.

Training your Tastes

By far the hardest, but also most important stage I went through was this one. Training my tastes to be satisfied with healthier foods. This is hard, and will require the most willpower of any of the stages. You can lose weight without doing this, but you cannot be “healthy” overall. If you do not go through this stage, the burden of losing weight will be placed solely on the activities stage, which can be done, but it makes it that much more demanding.

Details of my Stages

Now that I’ve given you a frame of reference with which to approach the rest of this article, I’d like to jump right in with the details of what I went through in each of the stages of my weight loss process.

Mental

As mentioned before, this was the easiest stage. It isn’t hard to feel bad about yourself and want to change. Heck, if you are human, you feel this way every day of your life about some aspect of your body, personality, position, etc.

What’s difficult is actually doing something about it. When you decide to act you have to have the correct mindset, otherwise you will fail. A parallel would be trying to write functional code in an object-oriented language. If your mindset and frame of reference is wrong, you will fail.

Everybody knows someone like this. A friend or relative who is unhappy with their weight, and who, unlike a lot of people, is trying to do something about it. They try the Paleo diet, they try the Atkins diet, they try to take pills that they bought at 3 a.m. from the home shopping network that will just make the fat “melt away.”

The problem is, what this friend or relative is doing is not going to work, and whatever they do in the future will not work! Not until they change the way they are thinking about weight loss.

Wanting to change is good, but you have to first understand that change cannot be for a day, or a month, or a year.

Change is something you do with the goal of it being forever. You might say to me, “Duh, I don’t want to be skinny and fit for just a year, I want to be skinny and fit for the rest of my life!” and that’s great. I want you to be skinny and fit the rest of your life too!

Training Your Mind

There is a problem with your thinking, though. And the problem is that in order for your body to change for the rest of your life, your mind has to change for the rest of your life as well.

A programmer can’t learn how to code simply by typing syntax over and over until muscle memory makes it easy to type a programming language—your brain has to be engaged in understanding the meaning of what you’re doing, otherwise you will never be a programmer. So why is it that we think we can lose weight without training our minds as we would with any other acquired skill?

Now, I’m not saying your mind has to change all at once right now, but you have to realize that just like how changing your body is a slow iterative process that happens over time, so is changing and training your mind and your thinking processes.

If you spent zero effort attempting to diet and exercise, but spent every ounce of mental energy convincing yourself that fast food is bad and that raw vegetables are delicious and good, I guarantee you would lose weight and be healthier than you would by trying to diet and exercise while craving a BigMac every waking moment.

The goal here is not to change the way you think overnight, or even before you start anything else, but rather just to recognize that working iteratively over time on your thinking is just as important as daily exercise. There is no magical overnight solution. If you want to change for life, then you have to be willing to invest a large amount of time and effort into changing.

Tip: An exercise that helped me a lot in this stage was just telling myself, out loud, that I was doing something unhealthy whenever I did it. I didn’t expect to stop doing it right away, I just didn’t hide anything from myself with ignorance or half-truths.

Habits & Skills

We often learn how to do certain things correctly without knowing why we do them that way. But people often want to know why they should eat a certain way or follow a specific workout plan. And if they don’t get an answer to ‘why’ that they understand, they may not want to follow that program.

When I was reading my first C programming book, I had no idea what inversion of dependency was, or why it was good, or even how to do something like that, even if someone with years of experience tried very carefully to explain to me why it is good, and why I should know about it. I was clueless.

When you are just barely starting to learn how to do something like losing weight and starting a fitness program, you need to understand that when you ask “Why?” you are likely to get a beginner answer. There may be a much more complicated answer that is harder to understand or explain but that answer is earned with time and practice.

If we fail to lose weight or get fit,  it’s usually because we are not training our brains with good habits.

Eating large portions of bacon every day, and nothing else, may be something you want to do, but it will not be healthy for you. You may lose weight in the short term, but you will not be healthier for it.

There are any number of things we tell ourselves in order to justify something we want, or to justify not doing something we dislike. You have to remove this weakness, and you remove it by training yourself in good habits and skills, without question.

These things do not have to be huge things—as with any trained set of good habits each one is likely to be very small and manageable.

I never used an elevator. Ever. To this day I will take the stairs unless something requires me to use the elevator.

  • I never parked in the first 10 spots closest to the store or business I was going to.
  • I never ordered a “large” size value meal from a fast food restaurant.
  • I never ate in the car while driving.
  • I never ate at the computer or while watching TV.
  • If I wanted to eat, I dedicated time just to eating, then went back to what I was doing.
  • I ate smaller, more frequent meals. I didn’t understand why this mattered, but a lot of people said it helped, so I did it.

Note: You may find your daily dietary schedule will change once you reach your target weight and go into maintenance mode, but this is a very different stage from weight loss. You may even find one meal a day is best for you in maintenance mode.

  • I made myself stand up from my desk and walk around for a minute or two every hour or two. I can’t imagine why this little bit of exercise would help, but I did it because a lot of more experienced people than I was said it would.
  • I did bicep curls sitting at my desk with my copy of Knuth’s Art of Computer Programming while I was thinking about a hard problem. Eventually I added volume two!
  • I started to try to stay standing as often as I could, work at a tall table, and even picked up the habit of pacing back and forth when I was thinking.

Tip: The added benefit to pacing is that it will likely drive your coworkers crazy!

There were countless other things that I did without question because I knew that even though I may or may not have fully understood why, I knew they would be good for me in the long run.

You have to train yourself in good habits and skills now in order to give you the foundation that you need later on when things actually get hard. For example, when you desperately don’t want to do your five-mile jog or eat another serving of chicken and brown rice. You have to have the practice and discipline engrained in your brain to just do what you know is right, and practicing on the little things makes this easier for the larger things later on.

Major Activities

This is where it gets hard. No more five minute walks or short “stand up and stretch” sessions. At some point you really have to start working on the hard things, and adding major activities to your weekly routine becomes a necessary step.

Just like any other step, starting out slow is a good idea. As I mentioned above, my first activity was making myself walk around the block every day, whether I wanted to or not. Come rain or shine, a busy work or school day, it didn’t matter; I made myself take a walk. Having had practice making myself follow the little rules made this easier. Besides, it’s just a walk, right?

Tip: An easy way to make this time productive is to get audiobooks to listen to, or practice explaining design patterns in your head. If you are a contractor or remote employee schedule a meeting that you can be on the phone for during this time. Be efficient and creative with the time and you’ll never notice that you aren’t sitting at your desk.

Over time my walks got longer and longer. I added a lap every few days, until I was walking for over an hour a day. Well, that consumes a lot of time, so being the efficiency-minded nerd that I am, I decided that I needed to start jogging.

Of course, I didn’t jog as many laps as I was walking; I would have had a heart attack. Just as with the walking laps, I started with one. I’d walk a lap to warm up, then jog a lap.

The first jogged lap was a nightmare. I hurt everywhere the next day. Not to mention the embarrassment that I felt, being overweight and bouncing down the street. But there was one thing I knew I had to do: keep going.

Just like the walking, rain or shine, busy day or not, party to get to or lazy evening at home, I always jogged my lap. Eventually, I added a second lap. That was a great day! The day I made two laps jogging around the block I celebrated with my roommate. I think I had a couple beers that night, which of course I had been trying to avoid.

Tip: If you find yourself craving the occasional drink while working on losing weight, hard alcohol has much fewer calories than beer or wine. During my years of weight loss I became quite the Scotch connoisseur, while refraining from that beer or glass of wine with dinner (but remember to always be responsible).

This pattern continued, and over time I added more and more laps. Eventually I was jogging for half an hour straight, not fast, or elegantly, and I was still bouncing down the street, but I was doing it, and that was amazing!

Tip: These triumphs are incredibly important; revel in them. Enjoying overcoming the challenges at each stage, and throughout the stages, is one of the primary fuels that propels you forward. This is no different than when you solve a hard coding problem, or learn a new design pattern. Your excitement and enthusiasm for technology is what drives you forward. Harness that same drive and enthusiasm with your physical fitness.

Taking it Up a Notch

It was at this point that I started feeling more and more comfortable with the idea of more strenuous activities. I had never worked out on weights before, so I gave that a try. I always loved the outdoors, so I gave more challenging hiking a try, and a co-worker who liked to cycle convinced me to buy a bike and go on rides with him.

At first all of those activities were great supplements, but still, I never skipped my jogging.

Eventually my “dabbling” in different activities turned into love of a few. I very much enjoyed weight lifting, and hiking. To this day elements of those activities are in my weekly routine.

Tip: One of the best ways to quickly overcome the soreness of any major physical activity is to do a light warm up exercise before anything strenuous, and full body stretching exercises after any activity.

This is the overarching idea here: I loved a few activities. When you are first getting into the major activities phase you are going to try things you hate, and that’s fine—just do them a little while and move on—but you have to find some that you like.

The habits that you developed before this are going to help you keep looking for and doing the things that matter for a while; not forever, but hopefully long enough that you find an activity that you love. And doing what you love is key, because the only exercise that you will keep doing is the one you enjoy, and the only exercise that counts is the one you keep doing.

Ultimately this process of self-discovery lead me to karate. So now my own exercise routine revolves around my continued pursuit of martial skill.

Would you still be sitting at a desk typing away into Emacs, Visual Studio, Eclipse, etc. if you didn’t absolutely love what you were doing? Of course not. In fact, most other human beings think we are all psychotic for loving what we do.Whatever physical activity you love, this is the stage where you have to find it, and embrace it. Without a major activity that you can embrace and love doing, no amount of willpower is going to carry you through. It is always important to continually strengthen your willpower by building skills and habits, but that is just the start.

Changing Your Tastes

By far the hardest of the stages is this one. Our tastes are ingrained in us throughout the duration of our entire lives and the longer we do something for, the harder it is to change. But, it is possible.

As I said above, this stage is incredibly important and difficult. The failure of this stage in most people’s attempts at dieting is the reason so many people gain back the weight that they have lost.

Again, we start out slow.

The very first thing that I did was to stop adding salt to food. Oh sure, I still ate BigMacs and fries, tacos and burritos(or sushi and salads when I was trying to be healthier), but I never added salt from a shaker or a packet. It’s a little thing, but it’s a start. I noticed a taste difference in some things, and in some things I didn’t.

It may seem odd to start with salt, given that it doesn’t necessarily add to your waistline, but there is method to the madness. For me the reason was twofold: I was worried about blood pressure and my heart health, and salt is one of three things that modern society consumes too much of, inundating our taste buds with more flavor than they know what to do with.

Just think to yourself, “What is my favorite snack when I’m sitting at the computer working/gaming/binge watching?” I bet for most people it has a ton of salt in it.

The other two things, and the next steps in my taste-changing process, are sugar and fat.

Sugar was the second thing to go. No more sugar in my coffee or tea, and on the rare occasions that I had a soda I drank diet. When I ate dessert, I picked ones with lower sugar content. Since I was trying to cut down on salt at this stage too, my snacks of choice tended towards unsalted nuts.

I’m not going to lie. At this point I was dying! It’s easy to think or say what needs to be done, and much harder to actually do it. I struggled to keep salt and sugar out of my diet. I had overwhelming temptations, and what’s worse, the cravings were stronger because I knew what I was doing to myself. I was trying to get rid of those things, forever. I was trying to train my brain to hate salty and sweet things.

This stage is not easy, and you will struggle with it a long time, but it has to be done. The previous two stages lead up to this. Up to this stage you have been practicing good habits, training your brain to have healthier thoughts, and reveling in the small and large victories that come along the way to give yourself mental fortitude—all just for this.

Note: Absolutely do not stop practicing the steps of the previous stages here, especially the self-congratulatory parts when you achieve some new level of health or fitness. This is critical to keeping yourself motivated.

I stalled.

Yup, it was too much for me. I liked salt too much. Sugar was easier for me, but I regressed on salt. Before I could even get to fatty things, I regressed.

It’s a Struggle

I ended up fighting my taste for salt for years. Sugar was easier to limit over time, mostly because my taste for salt and fat has always been bigger than for sugar. I went back and forth, and back and forth.

Eventually, I decided that I was making progress on sugar, and that was a good thing. I was always going to be fighting myself with salt and I knew it, so, I might as well be fighting my taste for fat at the same time. I added fat to the mental war.

It didn’t seem like I was doing well at first. I struggled with keeping excessive salt and fat out of my diet. I had a few things that were easy to love and healthy, like sushi without soy sauce, but you can’t eat the same thing every day.

Through my ups and downs with changing my tastes, I relied on mastery of the previous steps. I reveled in every victory that I could. I marveled that I was close to my target weight, and keeping the weight off. I hiked to the tops of mountains, took 40-mile bike rides, got up to 65 pound bicep curls, and yet I was still unhappy that I couldn’t get rid of my taste for fat and salt.

The Payoff

Then only a few years ago, I had a realization. I was out to dinner with my wife, and I ordered something with a sauce of some sort, I think it was a chicken dish. The whole time we were waiting for dinner to arrive, I was telling myself how unhealthy I was being, how the sauce was probably full of fat, salt and sugar, and I should have ordered a plain meat, or salad. Then dinner arrived, and I tasted it… and it tasted bad! I didn’t like it. For the first time in my life, I thought to myself, “This food is too rich.” I scraped the sauce off, and ate the chicken without it.

At first I thought it was a fluke, that the chef had messed up and put too much of something in the dish, but it happened again. A few months later we were out again, and I had trouble eating some of the food. It was too rich.

Over time I realized these weren’t accidents. These were direct results of me fighting the battle every day, and I was winning. It wasn’t fast, and I couldn’t tell a difference from day to day, but there it was. I was winning. I trusted the process, and followed it day to day, and over time I saw results.

I was happy for a month after I had that realization. Like, “Passed Distributed Systems advanced study 789 with an ‘A’ during my grad program” happy. Got my first developer job out of college happy. Got my first “Senior” Software Engineer job title happy.

So, of course, I celebrated, and embraced the joy, and used it to redouble my efforts.

I still struggle, I still have days where I regret my dietary choices. I gain a few pounds and lose a few pounds. But now, I am happy to do so, because I am winning.

My Major Guiding Principle

During my time going through the weight lose process I gained a guiding principle that I want to share. This was something that I only discovered in hindsight, but is likely one of the most important things that I was doing, unknowingly, all along.

The 75% Rule

This is the big one; the one piece of advice to rule them all. The 75% Rule.

We are all human. We are all fallible, and nobody has infallible willpower. Because of this, you have to tailor your process to be tolerant to when you will fail, and optimized to when you are doing everything right.

In retrospect, around the same time that I realized that I was “winning,” I realized something that I was doing and had been doing the whole time. I was using the 75% rule. It’s a simple rule. No matter what stage you are in, or what particular thing you are struggling with at the moment, when you are struggling you just have to make the healthy choice 75% of the time.

Let’s be honest, I am not superman. I skipped workouts. I ate junk food in the later stages and regretted it. Even the healthiest people have “indulgences” of some sort. But for me, it was easy for me to control myself when I knew I would be able to have a burger occasionally, or skip a workout every once in a while. Roughly ¼ of the time, I would get to be lazy or unhealthy. And it kept me strong, because now instead of thinking to myself, “I will never get things X, Y, Z that I love again!”, I knew I would occasionally.

It’s important to not abuse this rule though. It only applies when you are struggling. Not every decision of every day. “Should I eat junk for breakfast, no, should I eat junk for lunch, no, should I have that candy bar in the afternoon, no, should I have a large supreme pizza all by myself for dinner, yes! 75% rule!”… it doesn’t work like that.

When your willpower is high, and a decision is easy, you make the right decision because it’s easier to do so. When your willpower is low and you are struggling, that’s when you tell yourself, “I am on two out of four cravings, hold out for one more craving and I can indulge.”

A Lifelong Pursuit

Struggle is a part of life. It is what defines us, and sets us apart.

No matter how motivated you become, you will struggle to stay motivated, and to make the right choices. The things that I’ve learned, I believe, can help anyone going through this kind of life change, but I by no means have all the answers to always staying motivated, and overcoming all your health struggles.

And what’s a life-changing article without some old Asian wisdom thrown in? Right?

So here goes. Something that I’ve reflected on quite a bit in my years of martial arts training and in my physical fitness journey are a pair of quotes from Gichin Funakoshi, the Okinawan karate master responsible for popularizing karate on mainland Japan in the 1920s. The first is this:

“Karate is a lifelong pursuit” – Gichin Funakoshi

How many of us have dedicated our lives to technology, to programming, to writing, or to business? A dedicated life is a productive one, and passion drives that. You have to have passion for your health and fitness, and with that passion you will have the drive to pursue a lifetime of good health.

The second quote is this:

“The ultimate aim of Karate lies not in victory or defeat, but in the perfection of the character of its participants.” – Gichin Funakoshi

Shouldn’t perfection of character be what we all strive towards in our daily lives, in our jobs, and in our personal relationships? If we want to perfect our character, then we want to lead a healthy and fit lifestyle, not only for ourselves, but as an example to others.

If you have gotten this far then thank you for reading. I genuinely hope that this article and my experiences can help you to have the kind of healthy lifestyle that you want. If only one person reads this and is inspired then I am satisfied, and all the hours I’ve spent writing this and reflecting on my experience will have been worth it, not just for myself, but for you as well, that one person.

The post Using The 75% Algorithm to Change Your Life with Weight Loss appeared first on Simple Programmer.

]]>
https://simpleprogrammer.com/75-algorithm-weight-loss/feed/ 0
The Ultimate List of Programming Books https://simpleprogrammer.com/the-ultimate-list-of-programming-books/ https://simpleprogrammer.com/the-ultimate-list-of-programming-books/#comments Mon, 23 Mar 2015 15:00:00 +0000 https://simpleprogrammer.com/?p=13335 Quite often I am asked about the top programming books that I’d recommend all software developers should read. I’ve finally decided to put together a list of the programming books that I find most beneficial and that I think every programmer should read. Now, just like my Ultimate List of Developer Podcasts, this is my...

The post The Ultimate List of Programming Books appeared first on Simple Programmer.

]]>
Quite often I am asked about the top programming books that I’d recommend all software developers should read.

I’ve finally decided to put together a list of the programming books that I find most beneficial and that I think every programmer should read.

Now, just like my Ultimate List of Developer Podcasts, this is my list, so I get to make the rules. (Which means I get to advertise my book at the top of this list–actually both of them.)

First, off:

My most recent book is a massive tome called “The Complete Software Developers Career Guide.

And it is massive, weighing in at about 800 pages for the printed version.the complete software developer's career guide

I wrote this book primarily because there just wasn’t a good book out there–or really any book for that matter–which told software developers everything they needed to know about how to have a successful career in software developer and to answer all the common questions I get like:

  • How do I get started as a software developer?
  • How do I learn a new programming language?
  • College, boot camp, self study?
  • How do I deal with my asshole boss? My coworkers? Discrimination?
  • How do I find a new job? My first job?
  • How do I get a raise?
  • What do I actually need to know to be a software developer?
  • How do I MAKE MORE MONEY and advance my career?

I could go on and on, but I think you get the point. Anyway, the goal was to create the one stop how-to guide for all software developers, regardless of career level, to manage their careers.

The book has been a huge success so far actually debuting #5, yes that’s right, #5 on the Wall Street Journal Non-fiction Best Seller list on the week of it’s release.

It’s a book every software developer should have. Period. (And not just cause I wrote it.)

Next…

After reading all the books on this list, being in the software development field for over 15 years and training hundreds of thousands of software developers through my online courses at Pluralsight, I wrote my own book called “Soft Skills: The Software Developer’s Life Manual.”
sonmez_cover150
Now, obviously I highly recommend this book—but not just because I wrote it.
I wrote the book because I felt that there was a large gap of knowledge missing in the programming books that were out there.

There are many excellent books—as you’ll no doubt encounter on this list—but, there weren’t any books that provided a comprehensive treatment of the soft skills required to be successful as a software developer—and to live a better life in general.

So, that is what “Soft Skills: The Software Developer’s Life Manual” is. I wanted to write the book that I wished someone would have given me 15 years ago when I first started my career as a software developer.

Ok, that is enough plugging my own book. If you want to check it out, you can find plenty of reviews for it here.

(And before you binge read this whole list, you might want to check out my guide: 10 Steps to Learn Anything Quickly)

Foundational programming books

This first list of books are ones that I consider to be a good starting point and provide a solid foundation for any software developer:
codecomplete
Code Complete: A Practical Handbook of Software Construction, Second Edition

This book is one of the most transformative books I’ve ever read. Immediately after reading this book, the way I wrote my code and the way I thought about writing code completely changed.
The book is full of great advice about how to write good code, regardless of architecture or programming language. Code Complete goes into the details of the structure of writing good code. I’ve never found another book that even comes close to touching many of the topics in this book. I consider this book a must-read for all serious software developers. The book is a bit dated, but still has extremely valuable information.

Clean Code: A Handbook of Agile Software Craftsmanship

This is another one of those books that completely changed the way I wrote code. I can neatly divide my programming career into pre-Code Complete, pre-Clean Code and after. I recommend this book after reading Code Complete, because while Code Complete deals more with the structure of individual lines of code and methods, Clean Code deals with some of the same concepts, but at a slightly higher level.

It’s pretty difficult to read this book and not become a better programmer.

Structure and Interpretation of Computer Programs

I debated putting this one on the list. Is it really foundational? It depends on how solid of a foundation you want to have. If you want to have a really solid foundation, then the answer is a resounding “yes.”

The book is challenging. It deals with functional programming. It was written for the famous introductory programming course at MIT. But, I’d recommend you not only read this book, but go through all the exercises in it. It will be a difficult journey, but you’ll come out the other side a much better programmer than you were before.

Design Patterns: Elements of Reusable Object-Oriented Software

This classical book is critical reading to really understand what design patterns are and become familiar with the most common design patterns you are likely to encounter in your career. It’s not a particularly easy read and the descriptions and examples might be a bit difficult to follow—especially if you don’t have a solid grasp of UML—but, it’s a book I consider a “must read.” If you are having trouble with this book, you might want to start with “Head First Design Patterns.” which teaches the design patterns in this book in a much more digestible way—still, there is no substitute for the original.

Head First Design Patterns

Read the classic first, then read this one, then go back and read the classic one with a renewed understanding. This book makes design patterns much easier to understand. It’s also a useful book for learning how to teach complex topics and make them interesting.

Refactoring: Improving the Design of Existing Code

Although modern IDEs have automated many of the refactorings mentioned in this book, refactoring is still a very important concept to understand in order to write good, clean code—especially in today’s Agile environments. This book covers just about all of the major refactorings that all software developers should know how to execute in any code base. Learning how to refactor your code allows you to breathe new life into it and to have it improve over time as it is maintained, rather than rot.

Working Effectively With Legacy Code

Unless you are fortunate enough to always work on green-field projects, you’ll mostly likely encounter legacy code in your career—and lots of it. I included this book, because it is the foundational programming book on working with legacy code. If you are working on a large code base more than 5 years old, this book might be your new bible. Read it and take it to heart.

Professional development programming books

This section contains programming books that I have found most beneficial to my professional development as a software developer.
pragmatic programmer
The Pragmatic Programmer: From Journeyman to Master

When I first read this book, it wasn’t my favorite. I still don’t agree with everything said in the book, but even with my misgivings, I have to acknowledge this is a programming book that every software developer should read when they want to transition from being just a coder to something more. There is some extremely pragmatic advice in this book that will bestow upon you lessons that otherwise would take years or even decades to learn.

The Clean Coder: A Code of Conduct for Professional Programmers
This book is all about being a professional programmer. This is a tough read. A lot of developers won’t like this programming book, because the advice is sometimes difficult to swallow. But swallow it if you can, because Bob Martin, the author of the book, is a veteran in the industry and has managed to stay relevant decade after decade of pumping out code. I really found this book helpful in shaping my career and making tough decisions.

The Passionate Programmer: Creating a Remarkable Career in Software Development

This book was one of the main programming books that influenced me to treat my career in software development as a business rather than just something I did. The book is full of all kinds of wisdom about how to increase your skills, maximize your time, keep your career and passion alive and more. I highly recommend reading this book if you want to move beyond programming as just a job.

The Mythical Man Month

All those problems you thought were unique to your project, well I’ve got news for you, they aren’t. They are inside this book. If you want a very practical programming book about complex software development projects, this is it. This book is like a catalog of the most common problems that plague non-trivial software development projects and the book has more than stood the test of time.

Architecture based programming books

These are programming books that an aspiring architect or software developer who cares about architecture should read.
domain driven design
Domain-Driven Design: Tackling Complexity in the Heart of Software

Buckle your seat belt, this is a difficult read. The first time I read this book, I didn’t get it. The second time I read it, I sort of got it. It wasn’t until my third pass through the book that it finally clicked all the way. This book will help you learn how to create a maintainable architecture that is based on domain modeling. Once you learn what is in this book, you can’t go back. You won’t think about software development architecture in the same way again.

Patterns of Enterprise Application Architecture

If you are doing any kind of enterprise application development, you’ll find this book extremely useful. It contains great information about how to design and build an enterprise application from start to finish. What I found most useful though, was the many patterns contained in the book that are often seen in enterprise applications. This is a book I referenced all the time when I was building large enterprise applications for my job.

Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions

This is the absolute guide-book for implementing message bus or service bus architectures. Don’t let the name of the book fool you, this book is all about message buses and all of the patterns used to implement them correctly. If you are doing any kind of integration between applications or services using a bus, you will absolutely love this book.

Refactoring to Patterns

It is one thing to read and learn about design patterns, it is another thing to implement them. It is yet another thing to actually take existing code and refactor that code into design patterns. This is a programming book that teaches you—scratch that—shows you how to move existing code into patterns and how to even move it out of patterns. Should be on every architect’s bookshelf.

Agile programming books

These programming books are some of the best books on Agile development that I have found. I recommend them to anyone working in an Agile environment, whether you are using Scrum, Kanban, XP or something else.
agile software development
Agile Software Development, Principles, Patterns and Practices

Yes, this is another Bob Martin book, and it is excellent. There is also a C# version of this book. This book takes you through all the core tenants of Agile development without all the fluff. Not only that but it introduces the SOLID design principles which are fundamental to understanding how to write clean, maintainable code. This book was the book that convinced me to actually start doing pair programming.

Agile Estimating and Planning

So many teams get this wrong. This book shows you how to do it correctly. The first time I read through this book, I realized that sound principles could be applied to estimation and planning on an Agile team. Highly recommended for anyone working in an Agile environment.

User Stories Applied: For Agile Software Development

Another great Agile book that helps with a major trouble area: user stories. I’ve worked with some pretty crappy user stories when working on Agile teams, simply because no one knew how to make good ones or what user stories were actually supposed to look like. This book solves that problem.

Extreme Programming Explained

What I consider to be the classic Agile book. A little extreme for some—this is not SCRUM, this is real XP. This programming book is an extremely prescriptive description of how to implement extreme programming, but the ideas in this book can be applied to many different kinds of Agile environments.

Algorithm and interview question programming books

These programming books will make you better at writing algorithms and will help you pass interviews—especially programming interviews where you have to write code.
programming pearls
Programming Pearls

The classic book of programming problems. Read this book and actually do all the exercises. If you survive the ordeal, you’ll be a much better programmer and garner a deep understanding of algorithms and algorithm design as well as some critical problem solving skills.

Cracking the Coding Interview: 150 Programming Questions and Solutions

This book is not only one of the top-selling programming books on Amazon, it is one of the top selling books on Amazon, period. And for good reason. The book is full of great interview advice and real programming problems that will not only help you pass a coding interview, but make you a better programmer overall. Go through the book and do the exercises. If you can master the exercises in this book, it will be very difficult to stump you in a programming interview.

Introduction to Algorithms

This book is considered one of the best books on learning algorithms, and for good reason. It is a solid programming book for anyone interested in increasing their ability to write and understand algorithms, which is the core of writing code. If you are going to read any book on algorithms, start with this one for sure.

Language specific and programming language related programming books

This is a mix of really good language specific programming books and books that are related to programming languages in general. I know I’ve probably missed a few here, so help me out.
javascript the good parts
JavaScript the Good Parts

This book might become outdated as JavaScript evolves, but for now, this book is essential. JavaScript was a language that was never designed for the use it is used for today. That means there are quite a few pitfalls in writing JavaScript code. This book has saved me on more than one occasion. If you are going to write JavaScript, you are going to want to read this book.

Thinking in Java

This book not only teaches you how to start programming in Java, but it teaches you how to teach a programming language. I don’t think I’ve ever encountered a better book on learning a programming language than this book. Even if you have no interest in Java, I recommend reading it.

Effective Modern C++: 42 Specific Ways to Improve Your Use of C++11 and C++14

I’ve linked to the modern version of this book, but the whole series of older books is damn good. I learned so much from reading the original Effective C++, More Effective C++ and Effective STL books, that even though I don’t write any C++ code today, I still have fond memories of these books. I’ll admit, the earlier books probably won’t do you much good today if you are writing in modern C++, but if you are obsessed with becoming the best C++ developer possible, you have to read this updated version of the classic.

Effective Java

The Java counterpart is almost as good as the C++ original. Some of the recommendations are dated by the changes to the language, but overall this is still a really good book.

C# In Depth

Do you know C#? Do you really know C#? If you read this book you will. I’ve never read a book that dove as deeply into a language as this book does. Before I read this book, I considered myself an expert in C#. I would have given myself a 10. After, I realized how far from the mark my original estimation of my knowledge was.

Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages (Pragmatic Programmers)

I love this book, because it stretches you and makes you a more open-minded programmer. This is a programming book that has the potential to take you to the next level and see beyond pretty religious technology tendencies. This book helped me to see how similar so many programming languages are, appreciate their differences and see just how fast I could learn.

OPs, QA and deployment related programming books

These books are programming books related to anything outside the scope of normal programming activities, including testing, operations and deployment.
testing computer software
Testing Computer Software

Every developer should read this book to gain a good understanding of QA and testing. This book is very easy to digest, yet a comprehensive book all about testing. After reading this book, I was able to communicate with QA better, write more testable code and avoid defects by learning how to test my own code before throwing it over the wall.

Ship it! A Practical Guide to Successful Software Projects

Lots of great content and practices in this book. Some of them are a bit extreme, but they are all very effective. This book can help you take your software development shop to the next level. It’s a great book to read and then to give to your manager to highlight the value of some best practices like: continuous integration, automated testing, scaled back planning, etc.

Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation

I didn’t really believe continuous delivery was possible until I read this book. This book actually shows you how to build an entire system that will build and deploy tested code right into production. This book goes well beyond continuous integration and takes the entire delivery process into a continual flow. A programming book I highly recommend if you want to automate your entire deployment process—and trust me, you do!

Soft Skills and other fun programming books

These programming books are really not programming books at all, but are books that I have either found immensely valuable in my career, or books that most software developers have really enjoyed.
soft skills
soft skillsSoft Skills: The Software Developer’s Life Manual

Yes, this is my book. I mentioned it before, but I wanted to include it in its proper place as well. In this book I cover everything non-technical that a programmer could possibly be interested in, from career, to personal branding, blogging, learning, teaching, being productive, finances and even a bit on fitness and relationships.

How to Win Friends and Influence People

I really can’t praise this book enough. Yes, it has nothing to do with programming. You might be surprised to find this on a programming books list, but this is a life-changing book. As a software developer, you will deal with people during your entire career. If you learn how to deal with them effectively, you’ll have a much better go of it. So, I highly recommend reading this book. This book changed my life and set me on the path I am on now.

Code: The Hidden Language of Computer Hardware and Software

This is a fascinating book. Again, it’s not explicitly a programming book, but it is all about how computers work at the very lowest level. After reading this book, you’ll understand what the code you are writing is actually doing and how a CPU actually executes your code. This is both a fun and fascinating read.

Gödel, Escher, Bach: An Eternal Golden Braid

Another non-programming book on this programming book list, but a book that almost all programmers will find fascinating. This is a huge book that is one of the most pleasurable books I have ever read. I didn’t ever want to put this book down and I was extremely sad when I reached the end.

The War of Art

This one is another stretch. It is in no way a programming book—not even close—but it is a book that helped me achieve an extremely high level of productivity. This book is the reason why I can sit down and spend 4 hours writing this blog post. It’s an excellent book that will inspire you to be your best, and finally beat procrastination.

What programming books did I miss?

Any programming books that should be on this list?

If so, let me know and I’ll add them.

And if you’d like to see my “top 10” list of books I think every developer should read, I’ve put together a list you download.

Just click the button below to grab your copy:

The post The Ultimate List of Programming Books appeared first on Simple Programmer.

]]>
https://simpleprogrammer.com/the-ultimate-list-of-programming-books/feed/ 80
Wrapping Callbacks https://simpleprogrammer.com/wrapping-callbacks/ https://simpleprogrammer.com/wrapping-callbacks/#comments Sun, 06 May 2012 16:50:34 +0000 https://simpleprogrammer.com/?p=1528 I’ve recently had the problem of trying to display a progress dialog when executing an asynchronous operation and to dismiss that progress dialog when the operation completes.\n\nI wanted to build a way to do this that is generic to my application, so that it would work with any asynchronous operation in order to reduce duplication...

The post Wrapping Callbacks appeared first on Simple Programmer.

]]>
I’ve recently had the problem of trying to display a progress dialog when executing an asynchronous operation and to dismiss that progress dialog when the operation completes.\n\nI wanted to build a way to do this that is generic to my application, so that it would work with any asynchronous operation in order to reduce duplication of writing progress dialog logic everywhere in the code.\n\n11-290x300\n\n

\n\n

Looking at the problem

\n\nSo here is some basic pseudo-code of the problem.\n\n

\n\n\n\n

\n\nNow the problem with this code is that it would have to be repeated everywhere I want to make an asynchronous call and display a progress dialog.\n\nIf I want to do this in my application every time that I make an asynchronous call, I have to put this kind of code in many places in the application.\n\nYou can also see a mixing of responsibilities here.  We are handling UI related showing of a progress dialog split between an initial call and the callback.  It just seems a bit dirty to do things this way.\n\n

Breaking it down

\n\nSo how can we solve this problem?\n\nGo ahead and think of some way that you might be able to solve this.\n\n…\n\nOne of the best ways that I have found to solve any problem like this is to work backwards.\n\nLet us assume that any syntax we can think of is possible, and then only change the ideal syntax if it proves to not be possible.\n\nWhat do I mean by this?\n\nSimple, let’s come up with the way we want this code to look and we will worry about implementing it later.\n\nIt would be nice to be able to execute an asynchronous method and display a progress dialog with a one-liner, like so:\n\n

\n\n\n\n

\n\nIf we could just do this wherever we want to make an asynchronous call and automatically have the progress dialog shown and dismissed, life would be wonderful.\n\n

Solving the problem

\n\nIn order to solve this problem, we can do something very similar to a decorator pattern.\n\nWe can basically just wrap our callback method with a new callback that adds the functionality of dismissing our progress dialog.\n\nSo the idea will be that we will do the following steps in our ExecuteAsync method:\n\n

    \n

  1. Show the progress dialog
  2. \n

  3. Wrap our callback with one that dismisses our dialog and then executes the callback.
  4. \n

  5. Execute our asynchronous operation passing the new wrapped callback as the parameter.
  6. \n

\n\ngift-wrap-nature-lovers-easy-style-fabric-wrapping-1211-l\n\nHere is what this looks like in code:\n\n

\n\n\n\n

\n\nThis code actually looks more complicated than it really is.\n\nYou will need to understand how Action works though.  If you don’t, check out this post I did explaining Action and Func.\n\n

Understanding the solution

\n\nIt can be a bit hard to wrap your head around Action of type Action of type Result.\n\nLet me translate this to make it a bit easier.\n\nThe first parameter to ExecuteAsync is a method that takes another method as a parameter (the callback,) which takes a Result object as a parameter.\n\nGo ahead and read that over until you get it.\n\nSo, the idea here is that we are passing in the method that is going to do the callback as the first parameter to your ExecuteAsync method.\n\nThen we are passing in our actual callback as the 2nd parameter to ExecuteAsync.\n\nThe idea is that we are splitting apart the method and the callback it takes, so that we can insert our code to handle the dialog where we need to.\n\nNow we can just call ExecuteAsync and pass it our method and its callback and progress dialog code will automatically be handled for us.\n\n

Building on the idea

\n\nWe can expand upon this concept in several ways.\n\nOne thing we could do is also apply error handling logic to the callback wrapper method.  We could preprocess the result in some way before passing it to the callback.  This could allow us to display an error message or even retry a number of times before executing the callback.\n\nAnother thing we could do is to change the signature of the ExecuteAsync method so that it takes a type T instead of Result; this would allow us to handle any kind of return type and method, and the ExecuteAsync method would work with just about any asynchronous method call.

The post Wrapping Callbacks appeared first on Simple Programmer.

]]>
https://simpleprogrammer.com/wrapping-callbacks/feed/ 2
Making Switch Refactorings Better – Defaultable Dictionary https://simpleprogrammer.com/making-switch-refactorings-better-defaultable-dictionary/ https://simpleprogrammer.com/making-switch-refactorings-better-defaultable-dictionary/#comments Mon, 15 Aug 2011 04:25:52 +0000 https://simpleprogrammer.com/?p=1379 I’ve written before on the idea of refactoring a switch to a Map or Dictionary. There is one major problem that I have been running into though.  Switch statements and dictionaries are not functionally equivalent for one major reason… Switches allow for default I kept struggling with this when I would implement a dictionary to...

The post Making Switch Refactorings Better – Defaultable Dictionary appeared first on Simple Programmer.

]]>
I’ve written before on the idea of refactoring a switch to a Map or Dictionary.

There is one major problem that I have been running into though.  Switch statements and dictionaries are not functionally equivalent for one major reason…

Switches allow for default

I kept struggling with this when I would implement a dictionary to replace a switch.  How can I deal with the default case?

There are of course many ways to deal with the default case in a dictionary or map, but I didn’t really like any of the solutions because they either required me to remember to check to see if my entry was in the dictionary before looking it up, or to rely on catching an exception.

Let me give you an example:

Converting this to a dictionary we get something like:

So clunky, just to handle the default case.

Would be much better do something like this:

Well now you can!

Enter DefaultableDictionary!

Also the first thing I ever put on GitHub!

The idea is pretty simple, I am just creating a decorator for IDictionary.

The DefaultableDictionary has a constructor that takes an IDictionary and a default value.

It then delegates all of the methods to the passed in IDictionary reference.  For the methods that look up a value, it handles returning the default if the key doesn’t exist in the dictionary.

I created an extension method that lets you just put a .WithDefaultValue() on the end of your dictionary declaration in order to auto-magically give you a DefaultableDictionary back with that default value.

Sleep well my friend

Knowing that you can not create a dictionary that has a default value which is returned instead of throwing an exception if the key passed in is not found.

I have no doubt that in 3rd world countries children are still starving, but in 1st world countries children with VS Express hacking away at iPhone applications using MonoTouch will not have to catch exceptions from dictionaries that do not know how to just return a default value.

So now there is no excuse!  Refactor those switches!

The post Making Switch Refactorings Better – Defaultable Dictionary appeared first on Simple Programmer.

]]>
https://simpleprogrammer.com/making-switch-refactorings-better-defaultable-dictionary/feed/ 17
Back to Basics: Mock Eliminating Patterns https://simpleprogrammer.com/back-to-basics-mock-eliminating-patterns/ https://simpleprogrammer.com/back-to-basics-mock-eliminating-patterns/#comments Wed, 26 Jan 2011 14:09:32 +0000 https://simpleprogrammer.com/2011/01/26/back-to-basics-mock-eliminating-patterns/ In my previous post I talked about unit testing without mocks.  I gave some examples of how I had done this in some of my real code from PaceMaker.\n\nThis time I want to take a look at some of the common patterns we can use to extract parts of our code into dependency-lite or dependency-less...

The post Back to Basics: Mock Eliminating Patterns appeared first on Simple Programmer.

]]>
In my previous post I talked about unit testing without mocks.  I gave some examples of how I had done this in some of my real code from PaceMaker.\n\nThis time I want to take a look at some of the common patterns we can use to extract parts of our code into dependency-lite or dependency-less classes that we can unit test without needing mocks.\n\nI’ll have to admit, I haven’t really be practicing this approach for a long time, so my list of patterns is probably lacking, but these are some of the ones I kept seeing as I was working through the code.\n\nIf you have some ideas for other patterns or know of some already or have better names than what I have chosen, please let me know.\n\n

Pattern 1: Pull out state

\n\nIn many cases we can have complex objects that contain their own state often split across member variables.\n\nIf you find that a class has many methods that check some member variable and do one thing or another based on what value that member variable is set to, you might be able to benefit by extracting all the state changing logic into a separate class and creating events to notify the original class when the state changes.\n\nWe can then keep the new class as the single source of state for the class it came from and easily write dependency free (level 2) unit tests for the state class.\n\nFrom the perspective of the class you are pulling the state out of, we might turn:\n\n

\n\n\n\n

\n\nInto:\n\n

\n\n\n\n

\n\nObviously in this case there would be many ways the states get changed.  I haven’t included those here, but you can imagine how those would become part of the new state class.\n\nattack-penguin\n\n

Pattern 2: Method to class

\n\nOften I have found that I can’t find a way to extract all of the logic out of a class into one cohesive class, because of multiple interactions inside the class.\n\nWhen I encounter this problem, I have found that I can usually identify a single large method that is using data from dependencies in the class to perform its logic.\n\nThese methods can usually be extracted to be their own new class.  We can pass in the data from the dependencies the method was originally using instead of using the dependencies directly.\n\nGood candidates for this kind of pattern are methods which use multiple dependencies to get data in order to compute a single result.\n\nWhen applying this pattern we may end up with a very small class, containing only 1 or 2 methods, but we are able to easily unit test this class with state and dependency free unit tests (level 1.)\n\n

Pattern 3: Pull data sources up

\n\nIt is often the case that we have dependencies in a class that exist only to provide some sort of data to the actual logic in the class.\n\nIn these situations it is often possible to pull the source of the data up and out of the methods that use the data and instead pass in just the used data.\n\nPerforming this refactoring allows us to have methods in our class that do not use the dependency in the class directly, but instead have the data that dependency class provided passed in.\n\nWhen we do this, it opens up the ability to write clean and simple unit tests without mocks for those methods in the class or to apply the “Method to class” pattern to extract the method into its own testable class.\n\nAs a first step to refactoring my code to make it easily unit testable, I will often scan the methods in the class to find methods that are only using data from dependencies, but not manipulating the state or sending commands to the dependencies.  As I am able to identify these methods, I can apply this pattern to remove the dependencies from the methods.\n\n

Pattern 4: Gather then use

\n\nOften we find that we cannot pull a dependency out of a method because that dependency is being manipulated inside of a loop or in the middle of some process.\n\nIn cases like these, we can often gather all the data that will be used to manipulate the dependency in some form of a collection and then reiterate through that collection to perform the manipulation on the dependency.\n\nA good way to envision this is to think about two people mailing letters.  In one scenario we might have the first guy stuffing the envelope and the 2nd guy sealing the envelope.\n\nWe could carry on this process of 1st guy stuffs, 2nd guy seals for each letter we want to mail, but the process is dependent on both guys being present and working.\n\nIf we change it so that the first guy stuffs all the envelopes first and gives that stack of stuffed envelopes to the 2nd guy, they can do their jobs independently.\n\nBy applying the same idea to algorithms in our code, we can take a single method and break off the parts that don’t rely on dependencies to test independently or even move to their own classes.

The post Back to Basics: Mock Eliminating Patterns appeared first on Simple Programmer.

]]>
https://simpleprogrammer.com/back-to-basics-mock-eliminating-patterns/feed/ 6
How to Solve Programming Problems https://simpleprogrammer.com/solving-problems-breaking-it-down/ https://simpleprogrammer.com/solving-problems-breaking-it-down/#comments Sat, 08 Jan 2011 22:46:43 +0000 https://simpleprogrammer.com/2011/01/08/solving-problems-breaking-it-down/ Right before the holidays, I said that you had better learn how to solve programming problems.\n\nThis time I am going to try and give you some good tools to enable you to get good at solving programming problems.  (Really algorithm type problems specifically.)\n\n Common mistakes \n\n\n\nWhen most programmers are given a programming problem in an...

The post How to Solve Programming Problems appeared first on Simple Programmer.

]]>
Right before the holidays, I said that you had better learn how to solve programming problems.\n\nThis time I am going to try and give you some good tools to enable you to get good at solving programming problems.  (Really algorithm type problems specifically.)\n\n

Common mistakes

\n\nlolcatthink\n\nWhen most programmers are given a programming problem in an interview, they make several key mistakes.  The most severe of those is the improper allocation of time.\n\nIf you have heard the saying “measure twice and cut once,” then you are probably familiar with the idea of spending upfront time to make sure something is done right, rather than diving right in.\n\nThe most common mistake I see when conducting interviews or watching someone try to solve a programming problem is they try to start writing code as soon as possible.\n\nYou must resist this urge.\n\nYou really want to make sure you take enough time to understand the problem completely before attempting to solve it.\n\nAnother big mistake is trying to over solve the solution on the first iteration.  Keep it simple, don’t try to get fancy.\n\n

A simple set of steps

\n\nI am going to give you a simple set of steps to follow which you can use for any algorithm type programming problem.\n\n

    \n

  1. Read the problem completely twice.
  2. \n

  3. Solve the problem manually with 3 sets of sample data.
  4. \n

  5. Optimize the manual steps.
  6. \n

  7. Write the manual steps as comments or pseudo-code.
  8. \n

  9. Replace the comments or pseudo-code with real code.
  10. \n

  11. Optimize the real code.
  12. \n

\n\nAs much as 70% of our time should be spent in steps 1-3.\n\nLet’s look at each step.\n\n

Read the problem completely twice

\n\nThis is the single most important step.  You may even want to read the problem 3 or 4 times.\n\nYou want to make sure you completely understand the problem.  A good test of this is whether or not you can explain the problem to someone else.\n\nI cannot over-emphasize how important this step is!\n\nIf you don’t understand the problem, you cannot solve it.  Do not worry about wasting time here, because the better you understand the problem, the easier it will be to solve it.\n\nIf you are given any examples along with the problem, make sure you have worked through the examples and understand why the answers are correct for each one.\n\n

Solve the problem manually

\n\n

\n\n\n\n
I am going to tell you perhaps the biggest secret in programming.\n\n

“Nothing can be automated that cannot be done manually!”

\n\nProgramming is automation plain and simple.  You may have the ability to skip the manual steps and jump directly to code, but there is a manual process which is the foundation of any code you write.\n\nIt is very important to solve the problem manually first, so that you know what you are going to automate, otherwise you are just slinging code around.  Which while can be fun, will make you look like an idiot in a programming interview and will probably cause you to sweat profusely.\n\nI recommend that you solve the problem with at least three different inputs to make sure you really understand your solution and that it will work for more than one case.\n\nI often use a Mathematical Induction approach if possible.  Using this approach I might try and solve for 1 first, then for 2, then for n.\n\nAlso don’t forget to look for corner cases and edge cases and do any examples for those kind of cases you can think of.\n\nIt’s very important that when you solve a problem manually, you recognize what your brain is actually doing to solve the problem.  You may need to write out all the things you are normally storing in your head.  You want to be aware of each step, it is easy to gloss over them.\n\nLet’s look at a very basic example, reversing a string.\n\nIf I give you a string “Zebra”, and ask you to reverse it, most people will do the following manual steps.\n\n

    \n

  • Write “Zebra” down.
  • \n

  • Start a new word, and put “a” as the first letter.  (Why –> because it is the last letter, we want to start here)
  • \n

  • Put “r” down as the 2nd letter.  (Why –> because it is the next letter backwards from the last letter we copied)
  • \n

  • Put “b” down as the 3rd letter.  (Why –> same as above)
  • \n

  • Etc
  • \n

\n\nNotice how I write down each little step and why.\n\n

Optimize the manual solution

\n\nPeople often don’t realize how valuable this step is.  It is much easier to rearrange and reconstruct and idea or algorithm in your head than it is in code.\n\nIt’s well worth the effort to try and optimize the actual solution or simplify it when it is still in the most easily malleable state.\n\nWhat you want to do here is figure out if there is another way you can solve the problem easier, or if there are some steps you can cut our or simplify.\n\nLet’s look at our string reversal example and see if we can simplify the steps.\n\nWe should be able to immediately recognize that we can use a loop here to reduce the manual steps.  Our duplicate why’s for most of our steps tell us that we are doing the same thing over and over for each step, just with different data.\n\n

    \n

  1. Write “Zebra” down.
  2. \n

  3. Start at the last letter in the word and create a new empty word.
  4. \n

  5. Append the current letter to the new word
  6. \n

  7. If there is a previous letter, make the previous letter the current letter and start back at 3.
  8. \n

\n\nLook how close we are getting to code at this point.  You should be tempted to actually write the code for this.  That is good, it tells you that you have solved and simplified the problem well.  Writing code should now become very easy.\n\n

Write pseudo-code or comments

\n\nMany times you can skip this step if you have a really good handle on the problem or your previous steps already created a detailed enough description of the solution that coding it is already a 1 to 1 translation.\n\nIf you are a beginner or struggle with these kinds of problems, I would go ahead and take the time to do this step anyway though.\n\nWhat we want to do here is capture all the steps we created and now either put them into our editor as comments or write them as psuedo-code that we can translate to real code.\n\nBy doing this, we can know exactly what the structure of the code we are going to write is going to look like which makes the job of filling in the actual code later trivial.\n\nLet’s look at some psudeo-code for reversing a string.\n\n

// NewWord = “”\n\n// Loop backwards through word to reverse\n\n//   NewWord += CurrentLetter\n\n// Return NewWord

\n\nPretty simple, but the key thing we have done here is outlined the structure of the code we will write to solve the problem.\n\n

Replace comments with real code

\n\nThis step should be extremely easy at this point.  If you have done all the other steps, this step involves no problem solving at all.\n\nAll we do here is take each comment and convert it into a real line of code.\n\nTaking the string reversal, we might end up with something like this.\n\n

\n\n\n\n

\n\n1 for 1 translation of the comments we created above for real code.\n\nIf you struggle here, there are usually two possible reasons:\n\n

    \n

  1. You didn’t break down the problem into small enough steps
  2. \n

  3. You don’t know your programming language well enough to do the conversion
  4. \n

\n\nIf you didn’t break the problem down enough, try going back to the second step and being as meticulous as possible.  Write out each and every single step.  I know it is a pain, but do it, believe me it will be worth the effort.\n\nIf you don’t know your programming language well enough to do the translation, you may need to brush up here on some basic constructs.  Any language you expect to be able to solve algorithm type problems in, you should know how to do the following things:\n\n

    \n

  • Create a list
  • \n

  • Sort a list or array
  • \n

  • Create a map or dictionary
  • \n

  • Loop through a list, or dictionary
  • \n

  • Parse strings
  • \n

  • Convert from string to int, int to string, etc
  • \n

\n\nIf you don’t know how to do all of these things.  Stop what you are doing now and learn them. It’s not a very long list, and the benefits will be profound.\n\n

Optimize the real code

\n\nSometimes this step isn’t necessary, but it’s worth taking a look at your code and figuring out if you can cut out a few lines or do something simpler.\n\nThis is also a good place to make sure all your variables are named with long meaningful names.  I cannot stress enough how important having good names for your variables and methods is for helping the person evaluating your code to understand what you were trying to do.  This is especially important when you make a mistake!\n\nI won’t give an optimization for our trivial example of a string reversal, but a word of advice here is not to get too tricky.  Just try to mainly simplify your code and get rid of duplication.\n\n

A few final tips

\n\nIf you follow this template for solving algorithm type problem, you should do very well in programming interviews, but the key to doing so is having confidence in this process.\n\nThe only way you are going to have confidence in this process is to practice it.  It takes a good amount of faith to believe that spending 70% of your 30 minutes to solve a problem just thinking about the problem and not writing any code is the right approach, so make sure you have that faith when you need it.\n\nI’ve talked about using TopCoder to become a better programmer before, and I still recommend it.  Codility.com is another great site I have recently been introduced to.\n\nThere is one important step I did not include in the outline above, because I didn’t want to make the process any more complicated than it needed to be.\n\nMany times you will find that a problem itself involves multiple large steps or is very complicated.  In those instances, you will want to try and find a way to cut the problem directly in half and then following the process above for each half.\n\nThis method of tackling a problem is called “divide and conquer” and is quite effective.  A good way to know where to break a problem in half is to think about what part of the problem if already given to you would make solving the rest easy.\n\nThe programming interview is merely one battle in a larger war: marketing yourself. For the full lowdown, take a look at my course: How to Market Yourself as a Software Developer.

The post How to Solve Programming Problems appeared first on Simple Programmer.

]]>
https://simpleprogrammer.com/solving-problems-breaking-it-down/feed/ 23
Back To Basics: Sorting https://simpleprogrammer.com/back-to-basics-sorting/ https://simpleprogrammer.com/back-to-basics-sorting/#comments Wed, 08 Dec 2010 01:33:28 +0000 https://simpleprogrammer.com/2010/12/07/back-to-basics-sorting/ Why is sorting so hard?\n\nOne of the most common misunderstandings and frustrations I see from developers is around sorting.\n\nAlmost every developer has faced needing to sort a list of things in some manner in their development careers.  Many developers end up fumbling through it, looking for an example from the web and then copying that...

The post Back To Basics: Sorting appeared first on Simple Programmer.

]]>
Why is sorting so hard?\n\nOne of the most common misunderstandings and frustrations I see from developers is around sorting.\n\nAlmost every developer has faced needing to sort a list of things in some manner in their development careers.  Many developers end up fumbling through it, looking for an example from the web and then copying that example, not really knowing what they did or why it works.\n\nIf you fall into that category, or just want to know a little better how sort works, stay tuned, we are going to make it simple.\n\nharry-potter-sorting-hat\n\n

\n\n

Sorting algorithms?

\n\nNope.\n\nGreat for computer science.  You should have a basic idea of how they work, but unless you are writing some low level bit twiddling code on an integrated circuit, you don’t need to know about them.\n\nLet’s think of sorting algorithms as a black box.  You don’t need to know what the algorithm is or how it works, you just need to know that if you give the two things it requires it will sort your list for you.\n\nWhat two things do all sorting algorithms, regardless of implementation need?\n\n

    \n

  1. A list of things to sort
  2. \n

  3. A method to call to tell if object A comes before or after object B, or whether they are the same.
  4. \n

\n\nThat is all you need to know and give to a sorting algorithm implementation and it will do the rest.\n\nEvery modern programming language has at least one sorting algorithm and every single one of them has the exact two same inputs I mentioned above, a list to sort, and a comparison method.\n\nIt doesn’t matter if you are using C#, Java, Ruby or some other language, they all implement a sorting algorithm and need those two things.  And that is all they need from you.\n\nThe burden is off your shoulders.\n\n

Step 1: Find the sorting method

\n\nI’m going to do better than teach you how to sort in each language.  I’m going to show you how to figure out how to sort in a language.\n\nThe first step in doing that regardless of the language, is to find the method that sorts things.\n\nA good place to look is the list or collection object itself, since that is the most obvious place to put a sort routine.\n\nWhen we look up List in C#, sure enough we find Sort on there.\n\nOh noes!  So confusing!  It has 3 sort methods!  Which one do I call?  Agh!\n\nDon’t panic.  Remember what I said above.  Even though you see three signatures for the sort method, sort methods still only need two things.\n\nSort(), Sort(Comparison<T>), and Sort(IComparer<T>) still need just a list and a method to compare two of your objects.\n\nWe’ll dive into that more in a bit, now let’s look at Java.\n\nIf we look up ArrayList in Java, we don’t find a sort method.  Boo.  What were they thinking.  It’s ok though, googling for “Java sort” turns up Arrays.sort and Collections.sort.\n\nLet’s look at Collections.sort.\n\nThis time we see two sort methods, sort(List list), and sort(List list, Comparator c).\n\nAgain, nothing to be afraid of since we know the two things all sorting algorithms require from us.\n\n

\n\n

Step 2: Find the two things

\n\nSo if every sorting method needs the same two things from you, then all you need to do is figure out how to give it those two things.\n\nIn the C# and Java instances above, the first thing (the list of things to sort) is fairly obvious.  In C# we saw that the sort method was on the list class itself, so we don’t even need to pass it the list of things to sort, it still needs it, but it knows where to find it.\n\nIn the Java instance the first parameter to both sort methods is a list.\n\nSee how easy we just made things?  We are already 50% there.\n\nSo really the only question left is how to provide the method that compares two of our objects.\n\nWhen we know what we are looking for, it is much easier to find and understand.\n\nLet’s break down each instance and figure this out.\n\nIf we look at C#’s Sort() method, without reading the documentation, we can probably guess two things.\n\n

    \n

  1. The list to sort is the list we are calling the sort method on.
  2. \n

  3. The objects in the list provide the comparing method.
  4. \n

\n\nThe first is obvious.  The second one is a little less obvious, but if you think about it, since the method takes no parameters the only possible thing that could be providing the method for comparison is the objects in the list.\n\nIf we look at the documentation for Sort(), we find that is true.  The objects in the list have to implement IComparableIComparable has one method, CompareTo, which takes one object and compares it to the other.  If you implement this interface on your object, you can sort a list of them.  Simple.\n\nFor Sort(Comparison<T>), we can easily deduce that what is passed in there must be the method to compare two objects, and sure enough it is.  If we want to use this method we just pass in a method of type Comparison<T> where T is the type of object we want to compare.\n\nWe can see that Comparison<T> is just a method that takes two of your objects and returns an int to indicate which is greater or if they are equal (1 = greater, 0 = equal, –1 less).\n\nThe final C# Sort(IComparer<T>) just takes an object that implements IComparer<T>.  Sure enough, IComparer<T> has one method that must be implemented, Compare.  That method has the same signature as Comparison<T> from above.\n\nNow, let’s look at Java.  You’re going to find it is pretty much the same thing.\n\nFor sort(List list), we can easily see that the list to sort is passed in as a parameter, but once again we have to find where we supply the method to compare two of our objects.\n\nSince it can’t be passed in, it must be… say it with me… on the object.  That is right!\n\nTurns out we just have to have our objects implement Comparable and then they can be sorted.  When we look at the Comparable interface, we see that it just has one method, CompareTo(Object o) and that method just takes another object to compare our object to and returns 1 if ours is greater, 0 if it is the same, or –1 if ours is smaller.\n\nNow let’s look at sort(List list, Comparator c).  In this case, we can see that the method to compare our two objects is passed in, but since we can’t pass methods in Java, Comparator is just an interface that we can implement that provides the comparison method.\n\nIf we look at the Comparator interface, we see it has one method we need to implement compare(Object o1, Object o2).  I’m sure you can guess what that method should return by now.\n\nSo regardless of the language, when you are looking at how to use a sorting algorithm, find the two things that it needs.  The list is usually obvious, but the method to compare is almost always implemented in one of three ways.\n\n

    \n

  1. An interface the objects being compared implement.
  2. \n

  3. A method that is passed in.
  4. \n

  5. An object that is passed in that implements a comparison interface.
  6. \n

\n\n

\n\n

\n\n

Step 3: Implement the method

\n\nAfter you have figured out how to pass your list and your comparison method to the sorting algorithm, you need to actually write the comparison method.\n\nIf you learn to write a comparison method you can use it for any sorting algorithm, since all comparison methods do the exact same thing.\n\nFortunately, this is easy as well, because comparison methods always do the exact same thing.  They take two objects and return whether the first one is larger, smaller, or equal to the second.  That is it.\n\nDon’t worry about sorting.  Remember what I told you about the sorting algorithm black box?  Let that sorting algorithm worry about sorting, all you have to do is decide whether 1 given item comes before a 2nd given item or if they are they same, nothing more.\n\nCan you do that?\n\nSort people on age?\n\nIf person1.Age > person2.Age return 1\n\nElse if person1.Age < person2.Age return –1\n\nElse return 0\n\nPsuedo-code, but pretty simple.\n\n

Wrapping it up

\n\nIf you can figure out what method you can use to sort in your language, find how to pass in the list of things to sort and provide the comparison method, and implement the comparison method, then you can sort!\n\nJust remember to not get overwhelmed and think logically about the two things that all sorting methods need from you, and you’ll see how simple the whole sorting thing really is.  \n\nYou can be the guy that everyone asks about sorting instead of the guy copying and pasting some sorting code from the internet that you aren’t really sure how it works.\n\nBy the way, in C#, I would recommend just using the LINQ extension method OrderBy.\n\nVery nice to do something like:\n\npeople.OrderBy(p => p.Age).OrderBy(p => p.Name);

The post Back To Basics: Sorting appeared first on Simple Programmer.

]]>
https://simpleprogrammer.com/back-to-basics-sorting/feed/ 2
Switch is Just a Fancy If Else https://simpleprogrammer.com/switch-is-just-a-fancy-if-else/ https://simpleprogrammer.com/switch-is-just-a-fancy-if-else/#comments Thu, 12 Aug 2010 15:07:40 +0000 https://simpleprogrammer.com/?p=1047 Sorry to rain on your parade.  I know that you just refactored that series of if-else statements into one switch statement and you’re feeling like you did your good deed for the day. Take a moment to rest on your laurels before I tear your laurels to shreds. Go ahead, I’ll wait. Okay, now let’s...

The post Switch is Just a Fancy If Else appeared first on Simple Programmer.

]]>
Sorry to rain on your parade.  I know that you just refactored that series of if-else statements into one switch statement and you’re feeling like you did your good deed for the day.

Take a moment to rest on your laurels before I tear your laurels to shreds.

Go ahead, I’ll wait.

Okay, now let’s get down to business.

Saying the same thing a different way

The problem with changing if-else statements into a switch statement is that nothing really has changed besides the dialect in which it was said.

It’s all apples!

apples

Now, switch is slightly better than if-else for maintenance purposes, but not much better.  Both constructs (switch and if-else) try to represent some form of data (a mapping) as code.

Now data and code are not clearly delineated.  But, in general we have a concept of what constitutes data and what constitutes code.

Data is some information that does not contain in itself logic.

Code is some information that is primarily instructions and logic.

For this reason, I say that switch statements and if-else statements are both trying to treat data as logic.  They are both code constructs that mix in data elements with logic elements and do not clearly separate the two, although a switch statement does a slightly better job of it.

Consider the most basic form of an if-else and switch statement.  The form in which you directly map one piece of data to another piece of data.

If “A” then return “kittens”, If “B” then return “puppies”…

Switch (data1), case “A”: return “kittens”, case “B”: return “puppies”…

When I rewrite it in this form, the parallel becomes much more clear.   We can also very easily separate logic from data.

Data:

  • ”A”
  • ”B”
  • ”kittens”
  • ”puppies”

Logic:

  • Map something of dataset1 to something of dataset2.
  • Return a mapped value.

The problem with either of these forms, (the switch or the if-else), is that both of them tend to mix logic and data together.

Why is it bad to mix logic and data?

Let me ask you a question.  Which is more likely to change?

Hopefully it is data and not logic.

Consider the Single Responsibility Principle (SRP.)

A module should have one and only one reason to change.  Ideally, we want to separate out logic from data so that we can change the two independently.

Sticking with our contrived example, suppose we wanted to make “A” map to “dinosaurs” instead of “kittens,” or we want to add more mappings.  We should be able to do this in a way that does not interfere with the logic at all or add new logic.

If we have an if-else structure, we will have to add more if-else constructs or change a data value that is inside of the method that is doing the logic.  The same applies for a switch statement.  We are not declaring our data one place and our logic another, they will be side by side, right next to each other in the code.

Suppose we want to change the logic so that instead of returning a value, we assign it to some variable, or reverse it.  Again, we are faced with changing logic in multiple places, in the same module as the data.

Consider the case where we want to read the data from a file or some other data source?  Is that possible with a switch or if-else structure?  Not really, because the data is essentially “hard-coded” into the logic.

What can we do about it?

So, by now hopefully you have gotten the point that your refactoring of the if-else into a switch statement didn’t really solve the basic problem of mixing data and logic together.

But now you have another problem.  You need to separate your data and logic so that they can change independently.  You want to be a good steward of the SRP.  You want to someday be able to read your data from a file or database, so that you won’t even have to recompile your code to change it.

On my next post, I will show you how to take switch statements and refactor them into a better form that separates data from logic.

I will talk about the different “forms” of the switch statement and why to choose a particular method of refactoring over another.

The post Switch is Just a Fancy If Else appeared first on Simple Programmer.

]]>
https://simpleprogrammer.com/switch-is-just-a-fancy-if-else/feed/ 3
News Flash: SQL Server Paging Still Sucks! https://simpleprogrammer.com/news-flash-sql-server-paging-still-sucks/ https://simpleprogrammer.com/news-flash-sql-server-paging-still-sucks/#comments Thu, 22 Jul 2010 14:12:13 +0000 https://simpleprogrammer.com/?p=1013 Last time I wrote some code to allow paging of stored procedure results in SQL Server it sucked.\n\nThat was about 3-4 years ago.\n\nI just wrote some code to do it again, and well…  It still sucks.\n\nPerhaps I’m doing it wrong, but if you are looking for, “how to implement paging in sql server”, or “how...

The post News Flash: SQL Server Paging Still Sucks! appeared first on Simple Programmer.

]]>
Last time I wrote some code to allow paging of stored procedure results in SQL Server it sucked.\n\nThat was about 3-4 years ago.\n\nI just wrote some code to do it again, and well…  It still sucks.\n\nPerhaps I’m doing it wrong, but if you are looking for, “how to implement paging in sql server”, or “how to page sql server stored procedure results”, or “sql server paging”, I’ll give you my best answer for it at this point.\n\npaging\n\n

How I roll with CTEs

\n\nCTEs or Common Table Expressions, are a pretty nice feature of SQL Server.  They are a bit complex, but basically they let you create a query and treat it as a table to select from.  They also allow recursive calls to themselves, which let you do cool things like query hierarchies of data.\n\nThis link offers a pretty good explanation of CTEs.\n\nAnyway, CTEs come in handy combined with the ROW_NUMBER() function to add the ability to page data from an existing stored procedure.\n\nThe basic idea here is to modify the original query by wrapping it inside of a CTE that adds a RowNumber column.\n\nThen we can select from that query the rows that are in the range we want.\n\n

Vegetables are good for you

\n\nLet’s look at an example:\n\n

\n\n\n\n

\n\nNow let’s modify this query to be pageable given we have the first and last record we want.  (first record = page number * rows per page, last record = page number + 1 * rows per page)\n\n

\n\n\n\n

\n\nOkay, so it is actually not that bad.\n\nA couple of notes to help understand what happened here.\n\n

    \n

  • ROW_NUMBER() requires an OVER clause which basically will determine how you calculate what the row number is.  In this case, we are going to sort by name.  So, the first alphabetical name will be row number 1, and so on.
  • \n

  • We’ve wrapped the query in a CTE and added an additional column so that we have a row number in our new virtual table.  (Think of the CTE as creating a temporary view for us.)
  • \n

  • We are selecting everything out of the original query that is in the range of rows we want.  (Depending on how you define your range you may use different equality operators.  If you range is inclusive, you would do <= and >= , and if it is exclusive it would be < and >.  In this case we are both.)
  • \n

\n\n

A word on total row count

\n\nIf you need the total number of rows so that you can pass that back to the pager in your code, then you will probably have to select the results from the CTE into a temporary table and return two result sets from it.\n\nI couldn’t really find a way to select the total rows and the data from a single CTE expression.  If you know a way, please let me know.

The post News Flash: SQL Server Paging Still Sucks! appeared first on Simple Programmer.

]]>
https://simpleprogrammer.com/news-flash-sql-server-paging-still-sucks/feed/ 6