1. Introduction
If you have ever tried to “just write a utility that sorts files into folders”, you know how it usually ends: 12 parameters, 7 boolean flags, and a magic string "backup2_final_final" suddenly appear in the code. A contract is a way to agree in advance on what exactly the program does and how it should behave in contentious situations, so that later you do not argue with yourself while staring at if (flag) { ... } else { ... }.
In this lecture we will formalize the File Organizer contract: which input parameters it accepts, which modes it supports, what it does on name conflicts, and what we consider correct behavior. In the next steps of the project, we will traverse directories, build a placement plan, and perform operations. But without a contract, it is like renovating an apartment without a plan: “it will look nice here, and why a wire is sticking out of the wall—we will figure that out later”.
2. What a contract means for a console utility
A utility contract is not a legal document; it is a practical specification. It answers: what goes in, what comes out, which rules, which guarantees, which constraints. If you express this via types and data structures, the Kotlin compiler becomes your ally: it does not just “build the program”, it helps you avoid doing something dumb.
For File Organizer, it is convenient to think of the contract as three layers:
- Configuration — what the user passed to the utility: where to read from, where to put things, how to act.
- Policies — how we resolve ambiguity: what to do on conflicts, how to treat files without an extension, what counts as an error.
- Correctness criteria — what we consider a successful run, which results we record, and what statuses look like.
In this lecture we will focus on the first and second layers, and touch the third just a bit, to prepare the ground for reporting and safe bulk operations.
3. Minimal set of input parameters
Before drawing classes and enums, it helps to write down, in plain language, which parameters the utility needs to behave predictably. It is important not to overdo it: the more parameters, the more ways to start the program incorrectly. But too few parameters—and behavior becomes “magical”, and magic in I/O usually ends in drama.
This set is enough for us:
| Parameter | Meaning | Example |
|---|---|---|
|
source directory where we look for files | |
|
destination directory (root) | |
|
copy or move | |
|
which extensions we care about | |
|
what to do if the target file already exists | |
|
“do not touch the disk”, planning only | |
Note: there are no “tricky” things here like “traversal depth”, “masks”, “regex exclusions”. That is intentional: today we build a prototype that is easy to understand and not scary to run.
4. Modes: COPY vs MOVE — one word, very different risk
From the outside, COPY and MOVE look almost the same: “in one case we copy, in the other we move”. But in terms of risk they differ like “make a copy of a document” vs “burn the original after copying”.
In COPY mode, the source files remain in place. If you messed up the extension filter or the target structure, it is annoying but usually reversible: you can delete the target folder and try again.
In MOVE mode, you physically relocate files. A configuration mistake here can cost more. That is why the mode must be explicit and type-safe, not “true means move, false means copy”. Two days later you will forget what true means, and a week later you will forget it is your code at all.
Let’s define an enum class:
enum class Mode { COPY, MOVE }
And that is it: the compiler will no longer let you “accidentally pass 3 instead of a mode”.
5. Conflict policy: what to do if the file already exists
The second major ambiguity zone is name conflicts. Imagine you want to put report.pdf into the target folder, but there is already a report.pdf there. What should happen?
If the program “just overwrites”, that can be a disaster. If the program “always skips”, you might not notice that some files were not processed at all. Therefore, the conflict policy must be part of the contract, not a random if somewhere in the middle of the code.
Two simple options are enough for us:
- SKIP: if the target file exists, do nothing; record it as skipped.
- BACKUP: if the target file exists, first try to create a backup, then continue.
Again, use an enum class so there are no “magic strings”:
enum class ConflictPolicy { SKIP, BACKUP }
6. Configuration as a single object: less chaos in signatures
When you write functions at the level of “collect candidates”, “build plan”, “execute plan”, it is very easy to end up with signatures like:
fun execute(sourceDir: String, targetDir: String, mode: String, dryRun: Boolean, allowedExt: Set<String>, ...)
The signature becomes longer than your weekday sleep. And you also start mixing up the argument order.
So let’s agree: configuration is one object. The most convenient option is a data class. And one more nuance: you can store paths as String, but Path is a more “honest” type. We have already worked with paths and know that string-concatenating paths is a ticket into the world of weird bugs. So in the config we will store Path, not String.
import java.nio.file.Path
data class OrganizerConfig(
val sourceDir: Path,
val targetDir: Path,
val mode: Mode,
val allowedExt: Set<String>,
val conflictPolicy: ConflictPolicy,
val dryRun: Boolean
)
Note: allowedExt is a Set<String>, not a List<String>. What matters to us is the check “is this extension allowed” (set membership), not ordering. Also, a set automatically removes duplicates: if the user enters jpg,jpg,JPG, after normalization it all becomes a single jpg.
7. Normalizing extension and mode input
User input is creative. Sometimes too creative. So in the contract it is important to separate two stages:
- Raw strings — what was typed.
- Normalized values — what the program actually works with.
Normalization is about trim(), lowercase(), and removing the dot from an extension. Let’s create small helper functions. They are short, but they greatly reduce the chance you will later spend an hour figuring out why JPG does not pass the filter.
fun normalizeExt(raw: String): String =
raw.trim()
.removePrefix(".")
.lowercase()
Now let’s parse the mode. We want to support input such as copy, COPY, move .
fun parseModeOrNull(raw: String): Mode? = when (raw.trim().lowercase()) {
"copy" -> Mode.COPY
"move" -> Mode.MOVE
else -> null
}
And the conflict policy as well:
fun parseConflictPolicyOrNull(raw: String): ConflictPolicy? = when (raw.trim().lowercase()) {
"skip" -> ConflictPolicy.SKIP
"backup" -> ConflictPolicy.BACKUP
else -> null
}
Notice the OrNull suffix: that is your own mini-contract. It immediately says: “this function may fail to parse”. And you do not have to crash with an exception at the parsing stage—sometimes it is more convenient to return null and then, in main, explain to the user what exactly was entered incorrectly. Today we are not building a full CLI parser, but the habit “parse gently, validate strictly” is useful to practice.
8. Fail-fast configuration validation: better to stop before bulk operations
The most dangerous mistake in utilities that touch the file system is to start doing something and only then “suddenly realize” the parameters were invalid. For example, sourceDir does not exist, or targetDir points to a file, or targetDir is inside sourceDir, and you start organizing the results of organizing recursively.
So we need a validateConfig(cfg) function that runs short checks and, if something is wrong, immediately stops execution. In Kotlin, preconditions require() and check() are perfect for this: they throw meaningful exceptions and are designed exactly for such situations.
Let’s implement basic validation:
import java.nio.file.Path
import kotlin.io.path.exists
import kotlin.io.path.isDirectory
fun validateConfig(cfg: OrganizerConfig) {
require(cfg.sourceDir.exists() && cfg.sourceDir.isDirectory()) {
"Source directory must exist and be a directory: ${cfg.sourceDir}"
}
require(!cfg.targetDir.exists() || cfg.targetDir.isDirectory()) {
"Target must be a directory (or not exist yet): ${cfg.targetDir}"
}
}
Note the style of the messages: we write them so the user sees the exact path that caused the problem. A message like “invalid argument” is useless in a file utility, because there are many arguments, and disk errors are mysterious even for adults.
Validation: “target not inside source”
This check is not mandatory for a minimal prototype, but it saves you from trouble so often that it is better to add it right away. Otherwise, you can get infinite growth of candidate files because you create new files in the folder you are traversing.
import kotlin.io.path.normalize
import kotlin.io.path.startsWith
fun validateDirsNotNested(cfg: OrganizerConfig) {
val src = cfg.sourceDir.normalize()
val dst = cfg.targetDir.normalize()
require(!dst.startsWith(src)) {
"Target directory must NOT be inside source directory. source=$src, target=$dst"
}
}
This already looks like a real contract: we are not just checking that folders exist; we are checking that the scenario makes sense and does not create a trap.
9. Result model for reporting
At this step we are not copying or moving yet, but it is useful for the contract to define in advance what we want to get as output. The reason is simple: as soon as you start writing execution code, you will start making decisions. If the result model is not defined, the decisions will be random, and the report will be “well… something happened”.
At minimum, we need a status and fields we can show to the user. For example: from where, to where, what happened, and if an error occurred—what it was.
enum class OpStatus { PLANNED, COPIED, MOVED, SKIPPED, FAILED }
data class OpResult(
val source: String,
val target: String,
val status: OpStatus,
val message: String? = null
)
Why do we have PLANNED here? Because we will have dryRun: a mode where we want to build “as if” results, but change nothing. From the report’s point of view, it is not “copy success”, it is a “plan”.
In a real project you could debate whether a separate status for dry-run is needed. But for a learning prototype it is convenient: you will see the difference in the report with your own eyes and will not confuse “we actually copied” with “we just estimated”.
10. Minimal main skeleton
Now we will assemble a minimal main that:
- reads values from the console,
- parses and normalizes,
- builds an OrganizerConfig,
- validates it,
- prints “what we are going to do”.
We are not traversing directories or performing operations yet—and that is intentional. Our goal is to feel that the contract already works and filters out invalid runs.
import java.nio.file.Path
import kotlin.io.path.Path
fun main() {
print("Source dir: ")
val sourceRaw = readln()
print("Target dir: ")
val targetRaw = readln()
print("Mode (copy/move): ")
val mode = parseModeOrNull(readln()) ?: return
val cfg = OrganizerConfig(
sourceDir = Path(sourceRaw.trim()),
targetDir = Path(targetRaw.trim()),
mode = mode,
allowedExt = setOf("jpg", "png", "pdf"), // hardcode for now
conflictPolicy = ConflictPolicy.SKIP,
dryRun = true
)
validateConfig(cfg)
validateDirsNotNested(cfg)
println("Config OK. dryRun=${cfg.dryRun}, mode=${cfg.mode}")
}
Yes, there is “hardcode for now”. That is fine at this step: we are learning the shape, not building the final input UX. In the next steps of the project, we can expand the config, but the foundation is already in place: a configuration object, normalization, and fail-fast validation.
11. Useful nuances
How the contract fits into the utility pipeline
When you start writing File Organizer end-to-end, it helps to keep a simple pipeline in mind. The contract is its input and its rules, and everything else is processing stages.
flowchart LR
A[Raw input strings] --> B[Normalization and parsing]
B --> C[OrganizerConfig]
C --> D[validateConfig: fail-fast]
D --> E[Next: collect candidates and plan]
This seems obvious until you write a utility “straight in the loop”: there, validation usually gets smeared across the code and stops being a guarantee.
Where to store the code
As the project grows, you start searching for functions. And if everything lives in a single file Main.kt, searching turns into a mini-quest. Kotlin recommends meaningful file names: if a file contains one class, it is logical to name it after the class; if it contains a set of related declarations, name it after what it describes.
For today’s prototype, we can agree on this minimal split:
- Config.kt: OrganizerConfig, Mode, ConflictPolicy
- Parsing.kt: parseModeOrNull, parseConflictPolicyOrNull, normalizeExt
- Validation.kt: validateConfig, validateDirsNotNested
- Main.kt: only assembling and running the scenario
This is not “architecture on steroids”; it is simply a way not to drown in your own code.
12. Typical mistakes when designing the File Organizer contract
Mistake #1: encode COPY/MOVE mode via Boolean.
It looks tempting: val move = true. But after a few days, such code reads like a riddle: does true mean “move” or “copy”? And if a third mode appears, Boolean stops being sufficient altogether. An enum class Mode makes the contract self-documenting.
Mistake #2: do not fix the conflict policy and decide ad hoc.
When name conflicts are handled in three different places, sooner or later you will get this situation: one piece of code skips, another overwrites, a third tries to create a backup. The user will see chaos. The conflict policy must be part of OrganizerConfig so the decision is consistent.
Mistake #3: mix parsing, validation, and execution.
A very common scenario: you read a string, immediately try to create a directory, immediately traverse files, and then in the process suddenly realize the mode is not recognized. For bulk operations this is dangerous: you might have already modified the disk before you discover the error. The correct approach is to build OrganizerConfig first, then validateConfig, and only then proceed to “touching files”.
Mistake #4: weak error messages.
The message “Invalid config” is not help. A good message should include the specific path and the specific condition: “target must be a directory or not exist”. This is especially important because file problems often depend on the environment: permissions, current directory, OS quirks.
Mistake #5: do not check that target is outside source.
Without this check, you can accidentally organize what is already organized: you create the target structure inside the source, traversal starts finding new files, and the utility does more and more “work” until you stop it manually. This is not a “bad algorithm”, it is simply an unfixed rule in the contract.
Mistake #6: store dirty extensions without normalization.
If you compare extensions as strings without lowercase() and removing the dot, then .JPG and jpg become different values, and the user will feel that the utility “sometimes works, sometimes doesn’t”. Normalization is cheap insurance against such bugs.
GO TO FULL VERSION