r/PHPhelp • u/fuckl0ve • Apr 17 '21
[Junior Developer] Can someone code-review my project?
I'm 16, junior developer who wants to get their first job as a Software Engineer. I was wondering if someone could code review my recent project, and give me feedback on how I can improve?
Thanks so anyone who checks this out, if you do find any bugs could you please use the issues area to report them. If you have any feature requests I can do which could help me improve, that's cool too.
7
u/FordyO_o Apr 17 '21
Add tests!
1
u/fuckl0ve Apr 18 '21
Added :)
1
u/FordyO_o Apr 18 '21
Cool, does your code handle mixed cases properly for detection e.g.,
iAmCamel-and-kebab
Think of edge cases like this and add tests for them, that way if you do something like add new cases you can immediately check all the cases which have been broken before
Also I think for the "contains character other than" fn you should use regex e.g.
preg_match('/[^' . $needle . ']/')There are also various places you've used "==" and not "===", this works but it's better to get in the habit of using triple equals, it reduces the likelihood of weird type conversions messing up your logic.
4
Apr 17 '21
Awesome job! You said "junior", so when I clicked the link I expect to see some unreadable spaghetti. So I was really surprised by how good it was. Within seconds of opening this, I could see what the project was for, and how it was doing it. There are standard design patterns, names, code styles. There's a good use of interface. This would get a good score in terms of SOLID.
Two bits of feedback: Firstly, what would you need to change if you added a new encoder? Is there a way you can reduce that?
Secondly, there's something about the trait and the functions that I didn't like. The functions are a bit inconsistent - why are these functions, where everything else is objects and methods? (Functions have a difficult time in the land of Composer, so you tend not to see them in libraries of this kind.) And the trait feels like a service that should be injected. I wonder if this is all caused by the encoder trying to do too much: it's first trying to detect the case, then convert it. I'd push these responsibilities onto the client:
$existingCase = (new CaseDetector())->detect($string);
$encoded = (new CaseEncoder())->encode($string, $existingCase, 'camel');I'm guessing some unit tests would both help understand those problems better, and guide you to a solution.
I can see this code being useful as a library working with a framework like Laravel or Symfony, or with a testing system like PHPUnit. How would I configure the library to do that?
Well done on getting this released, it's a hell of a lot more valuable than anything I did when I was 16.
1
u/fuckl0ve Apr 18 '21 edited Apr 18 '21
Thanks! Check out my recent merges from develop branch, added tests, readme, refactored a little and its now cleaner than ever!
I took your idea about separating detection and conversion :) also the functions are methods now.
2
u/footballisrugby Apr 17 '21 edited Oct 16 '26
The original post content no longer exists here. The author used Redact to remove it, exercising their right to control their data & privacy.
Busy enjoy familiar relieved glorious swim pot hammock apparatus
2
2
u/footballisrugby Apr 17 '21 edited Oct 16 '26
The original post content no longer exists here. The author used Redact to remove it, exercising their right to control their data & privacy.
Theory violet knee violet friendly alive airport liquid
7
Apr 17 '21
Needs docblocks
Extract consts please
Describe arrays and what their keys are
3
u/AcousticDan Apr 17 '21
No code needs docblocks. Especially now that we have typed properties. Properly name your classes and functions and your code documents itself.
6
Apr 17 '21
Hard disagree. Fitting the entire explanation of what a method does into the name alone is a slippery slope that leads to a hard to maintain codebase. Even worse, needing to open the implementation to figure out what a methods doing
Look at any real code or libraries by real professional companies and you'll find that self-documenting code is just one piece in maintainability
0
u/AcousticDan Apr 17 '21
Fitting the entire explanation of what a method does into the name alone is a slippery slope that leads to a hard to maintain codebase.
Is it? It's not difficult if you maintain that a function does a single task. If you have to explain the code you write with comments, you've done a bad job. Sure, some comments are necessary, like "what the hell does this regular expression do?" But other than that, they're superfluous.
Look at any real code or libraries by real professional companies
I guess I don't write real code for a real company. TIL
0
Apr 18 '21
If your company is ok with no docblocks then i simply think your code standards are not good enough. You are defending a weird position, man.
So all of those google, laravel, synfony libraries' docblocks are superfluous? They're all wrong and you're right?
I just feel like anyone with enough real world experience maintaining not-insignificant codebases would obviously agree that docblocks are better than no-docblocks.
If your argument is that docblocks are a code smell of bad code or something i dont know what to tell you.
1
u/AcousticDan Apr 18 '21 edited Apr 18 '21
I'm saying 99% of the time, they're not necessary.
If your company is ok with no docblocks then i simply think your code standards are not good enough.
Maybe our code standards are just better?
Show me some code that absolutely needs docblocks and I'll show you it doesn't.
2
Apr 18 '21
one of the most widely used php classes
https://laravel.com/api/5.8/Illuminate/Database/Eloquent/Model.html
you're telling me
getAttributeValueis clearer without the descriptionGet a plain attribute (not a relationship).Should they writenotARelationshipin the method name too?
isDateAttributeis clearer without the descriptionDetermine if the given attribute is a date or date castable. Should they writeisDateOrDateCastable?The extra few words in a docblock sentence makes the code way more understandable. Please don't tell me you actually think that class would be better without allll of the descriptions and explanations listed on that page.
1
u/equilni Apr 18 '21 edited Apr 18 '21
https://github.com/illuminate/database/blob/8.x/Eloquent/Model.php
Let's take a look at the same class.
Type declaration would remove docblocks.
First property would be clearer without the docblock by using Nullable Type and updating the name. It's a "connection name", so name it accordingly.
/** * The connection name for the model. * * @var string|null */ protected $connection;Changed to:
protected ?string $connectionName;Further down, there is:
/** * The "type" of the primary key ID. * * @var string */ protected $keyType = 'int';Issue here, if you work with SQL, there are many KEYs, so adding more information to the variable helps later on. What kind of key - Primary. Reworked:
protected string $primaryKeyType = 'int';Update the method. The comments here don't match the property for a primary key, as the key may or may not be auto incrementing (see the next example):
/** * Get the auto-incrementing key type. * * @return string */ public function getKeyType() { return $this->keyType; }To:
public function getPrimaryKeyType(): string { return $this->primaryKeyType; }Here is one more:
/** * Indicates if the IDs are auto-incrementing. * * @var bool */ public $incrementing = true;To me, this sounds better:
public bool $isIncremental = true;Now the method:
/** * Get the value indicating whether the IDs are incrementing. * * @return bool */ public function getIncrementing() { return $this->incrementing; }Change to:
public function isIncremental(): bool { return $this->isIncremental; }Line 1016:
if ($this->getIncrementing()) { $this->insertAndSetId($query, $attributes); }Would be:
if ($this->isIncremental()) { $this->insertAndSetId($query, $attributes); }1
Apr 19 '21
the one right after that
/** * The relations to eager load on every query. * * @var array */ protected $with = [];would we name this
withEagerLoadRelationships? and if so, it isn't clear that that is eagerly loaded on every query.withEagerLoadRelationshipsOnEveryQuery? instead of chasing an ideal of "self-documenting code", a single docblock explains how it's used.i agree with most of your ideas btw. what i'm saying is that on top of those, why not add docblocks too? the original comment i replied too said:
No code needs docblocks
i just disagree with this. it's like saying "no one needs to use seatbelts" (if you drive perfectly, keep 360 vision at all times, and avoid accidents).
maybe in a perfect world with somehow absolutely perfect code that is never in the slightest ambiguous, but developers are imperfect humans, and it's more maintainable to just wear your seatbelt (docblock your damn code lol)
1
u/equilni Apr 19 '21
/** * The relations to eager load on every query. * * @var array */ protected $with = [];would we name this withEagerLoadRelationships? and if so, it isn't clear that that is eagerly loaded on every query. withEagerLoadRelationshipsOnEveryQuery? instead of chasing an ideal of "self-documenting code", a single docblock explains how it's used.
With the name
with, yes I would need some commentary what this is. With what exactly? I would name itloadedRelationsand keep the comment./** * The relations to eager load on every query. */ protected array $loadedRelations = [];what i'm saying is that on top of those, why not add docblocks too?
I am not against docblocks, but I think self documenting code is better. For one, you don't need the @var, @param, or @return anymore with type declarations.
Your example above:
isDateAttributeis clearer without the descriptionDetermine if the given attribute is a date or date castable. Should they writeisDateOrDateCastable?To me the docblock isn't needed and doesn't need to be renamed, but the
getDatesmethod does./** * Determine if the given attribute is a date or date castable. * * @param string $key * @return bool */ protected function isDateAttribute($key) { return in_array($key, $this->getDates(), true) || $this->isDateCastable($key); } /** * Get the attributes that should be converted to dates. * * @return array */ public function getDates() { if (! $this->usesTimestamps()) { return $this->dates; } $defaults = [ $this->getCreatedAtColumn(), $this->getUpdatedAtColumn(), ]; return array_unique(array_merge($this->dates, $defaults)); }Update
getDatestogetConvertableDatesmakes better sense and again doesn't need the docblock - keep it if you will. Simple change now makesisDateAttributeread better and self documenting.protected function isDateAttribute(string $key): bool { return in_array($key, $this->getConvertableDates(), true) || $this->isDateCastable($key); }→ More replies (0)
1
u/Toxic-Sky Apr 17 '21
Several people have given many good points about tests and similar. You have done a great job with this! May I recommend that you look into factory patterns? Speaking of patterns; I had this idea that it could be cool trying to identify the specific case with regex and trigger the correct en/decoder that way. Just a thought. :)
1
u/fuckl0ve Apr 18 '21
Thanks! Check out my recent merges from develop branch, added tests, readme, refactored a little and its now cleaner than ever!
I like your idea about removing the work needed to detect current cases, and I will look into regex!
1
u/sarc-tastic Apr 17 '21
public function encodeFromSnake(string $string) : string { return str_replace('.', '-', $string);
Looks decent. There are some mistakes too! The whole thing seems unnecessary for a elaborate wrapped str_replace!
1
u/equilni Apr 18 '21
Good work!
Quick thoughts and I will try not to repeat what others noted.
a) Nitpick - I wouldn't use App as the namespace. ReCase (no other PHP libs named this on Packagist) or something similar to your library would work better.
b) CaseDetection is not used in your codebase, only in the tests (CamelCase isn't using it...). No other docs on how to use it. Based on the codebase, I see this could be part of the main CaseConverter class or encoders. I would leave this in the development branch for now.
c) Note in your readme that this library only support the cases in your code as there are many other cases not covered - https://en.wikipedia.org/wiki/Naming_convention_(programming)#Examples_of_multiple-word_identifier_formats
d) The readme example doesn't include the second parameter, which per the code, is required. I don't understand why this is even needed though.... Leading into:
e) I would consider a different method for converting, like passing the encoder to the main class, good for adding your own encoders not in the library or even adding to a DI Container.
$pascalConverter = new CaseConverter(new PascalCaseEncoder());
$pascalConverter->convert('myText');If you decide to keep toCase(case), then my note above (c) needs to be documented in the readme. You note this is good if you don't like magic, but I like the previous way, written differently (changes the constructor):
$converter = new CaseConverter();
$converter->toPascal('myText');
9
u/albo87 Apr 17 '21
Congrats, it's very good code for a jr dev.
Some feedback
Add some unit tests
Add readme to tell me how to use this lib.
For the switch/cases with 0, 1, 2.. use the constants
I'd use a custom exception
You should add support for multibytes string
ctype support can be disabled, add it as a requirement in composer or you can use a polyfill (same with mbstring, use the mbstring polyfill)