Clean Code dalam Programming

Apa itu Clean Code

“You know you are working on clean code when each routine you read turns out to be pretty much what you expected. You can call it beautiful code when the code also makes it look like the language was made for the problem.”

— Ward Cunningham, developer dari wiki pertama

Penamaan yang berarti

user_detail = UserDetail.objects.get(user=request.user)

Penggunaan comment yang efisien

Penulisan Function

def my_profile(request):
""" View function for redirecting profile page"""
user_status = user_check(request)
if user_status == "NO ROLE":
return redirect('authorization:select_role')
if user_status == "NO DETAIL":
return redirect('authorization:detail')
if user_status == 1:
return my_profile_animallover(request)
if user_status == 2:
return my_profile_shelter(request)
if user_status == 3:
return my_profile_vet(request)
return redirect('homepage:index')
a = 0def assign_a(value):
global a
a = value
assign_a(4)

Penggunaan Error Handling

# memakai exception
try:
user = User.objects.get(email=request.user)
detail = UserDetail.objects.get(user=user)
return detail
except:
return "NO DETAIL"
# memakai if-else
user = User.objects.get(email=request.user)
if user is not None:
detail = UserDetail.objects.get(user=user)
retun detail
except:
return "NO DETAIL"

Penerapan TDD

DRY (Don’t Repeat Yourself)

def my_profile_vet(request):
user = authenticate(username='dummy', password='12345')
if user is None:
return redirect('homepage:index')
return render(request, 'vet_homepage.html')
def my_profile_animallover(request):
user = authenticate(username='dummy', password='12345')
if user is None:
return redirect('homepage:index')
return render(request, 'animal_lover_profile.html')
def authenticate_user(request):
user = authenticate(username='dummy', password='12345')
if user is None:
return redirect('homepage:index')
def my_profile_vet(request):
authenticate_user(request)
return render(request, 'vet_homepage.html')
def my_profile_animallover(request):
authenticate_user(request)
return render(request, 'animal_lover_profile.html')

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store