DEV Community

ちぇん
ちぇん

Posted on

Why don't we take in DDD to interview coding test.

I always feels the code of interview tests is not readable.
The shorten variable names, all logic packed in one method, etc. They are forbidden in real life coding but is it really okay in interview?

Watch example from leetcode.
https://leetcode.com/problems/longest-substring-without-repeating-characters/

The question is like this.

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

And the example answer is like this.

def lengthOfLongestSubstring(self, s):
    str_list = []
    max_length = 0
    for x in s:
        if x in str_list:
            str_list = str_list[str_list.index(x)+1:]
        str_list.append(x)    
        max_length = max(max_length, len(str_list))
    return max_length

Yeah, it's a short method and not difficult to understand but not perfect.
If you take in DDD and Value Object, it can be more readable.
Like this.

class Character : 
    def __init__(self , c:str) : 
        self.c = c

    def getValue(self) -> str : 
        return self.c

    def same(self , c) : 
        return self.c == c.c

class SubString : 
    def __init__(self) : 
        self.queue = []
        self.memo = {}

    def add(self, c:Character) :
        self.queue.append(c)
        self.memo[c.getValue()] = True

    def pop(self) -> Character : 
        c = self.queue.pop(0)
        self.memo[c.getValue()] = False
        return c

    def popUntil(self, c:Character) :
        popped = self.pop()
        while not popped.same(c) : 
            popped = self.pop()

    def contains(self, c:Character) : 
        return self.memo.get(c.getValue()) or False

    def length(self) : 
        return len(self.queue)


class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        subString = SubString()
        maxLength = 0
        for c in s : 
            character = Character(c)
            if subString.contains(character) : 
                subString.popUntil(character)
            subString.add(character)
            maxLength = max(maxLength , subString.length())
        return maxLength

wow it got longer than previous one.
However it's easier to understand the coder thought, is it?
Yeah, I know that time is limited in interview but I think the most important thing is to convey your thinking process to people, then try to take in DDD and you can express your thought more easily.

Top comments (1)

Collapse
 
mgce profile image
Mateusz Gajda

DDD was created to better describe and design business processes. What we have here is the implementation of an algorithm and DDD is not applicable in this context. What you're writing about is simply dividing responsibilities into individual classes.