dongming0505 2018-07-06 10:31
浏览 1325

状态 - 要使用哪种数据类型?

I'm currently looking at the code I've produced and I'm trying to improve its readability and quality. Here's an example of how I'd approach a simple problem, which I've always felt was a poor solution.

Users table with the below "statuses", or elevation levels in this example

  1. Employee
  2. Supervisor
  3. Admin

(these could be anything, for example, a project could have an "incomplete", "on hold" and "complete" status)

In the past, I've always stored this as an INT value then when printing out the accounts and their statuses, I will write a function to convert this back to text, to be printed on a page e.g.

if userLevel === 3 { return "Admin"; };

This has always felt like a bad solution, and it's not very flexible. The addition of any new types of account would require the function to be updated. This format also makes it very difficult to read page restrictions.

If I were to add the line:

if userLevel !== 2 OR 3 { // Redirect to error page };

You can see how this could become confusing down the line.

Recently I've started storing these "statuses" as a string purely so it's more readable. But now I've been getting more into Laravel, I wonder if I should have additional database tables devoted solely to this.

So my question - what is the appropriate data type for this kind of data, and what would be the ideal way to interact with it?

  • 写回答

2条回答 默认 最新

  • donglun1918 2018-07-06 10:47
    关注

    In legacy code I would use constants and basically bit doesn't really matter what kind of data is in it. It is readable, you can easily find usages and your IDE can help you out.

    In new code where you have a lot of business logic, you can create a create a small class representing the status so you can put the logic there.

    In DB - you can find couple of articles saying that enum is not a good idea. If you want to optimize a lot, tinyint can help you, but using a short string is good as well (I normally use it). Then you should translate it in a php ofc , I recommend the object approach described above.

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?